Búsqueda de sitios web

angular - Angular4+ mostrar/ocultar elemento hijo en la plantilla HTML


Estoy tratando de implementar una implementación simple de "pasar el cursor sobre un comentario para mostrar un botón de respuesta" en mi aplicación de Angular. ¿Hay alguna manera de lograr este efecto usando solo variables de referencia de plantilla?

Algo por el estilo de...

<mat-list>
  <mat-list-item *ngFor="let comment of comments" #SomeRefToThisParticularElement (mouseenter)="SomeRefToThisParticularElement=true" (mouseleave)="SomeRefToThisParticularElement=false">
    <h4>{{comment.text}}</h4>
    <p> 3 replies </p>
    <mat-icon *ngIf="SomeRefToThisParticularElement==true">reply</mat-icon>
  </mat-list-item>
</mat-list>

Obviamente, lo anterior no funciona porque Angular no te permite asignar o establecer variables de plantilla de la manera que he mostrado en el fragmento anterior. Pero me gustaría explorar opciones para lograr esto a nivel de la plantilla HTML.

¿Es este un buen enfoque para hacer esto?

Editar Haga clic aquí para un resumen de posibles soluciones.

Respuesta #1

prueba esto, mostrar y ocultar según el índice de desplazamiento de un arreglo.

<mat-list>
    <mat-list-item *ngFor="let comment of comments; let i = index" (mouseenter)="commentIndex= i" (mouseleave)="commentIndex = -1">
        <h4 mat-line>{{comment.text}}</h4>
        <p mat-line style="font-size:x-small; color:rgba(0, 0, 0, 0.54)"> 3 replies </p>
        <mat-icon *ngIf="commentIndex == i">reply</mat-icon>
    </mat-list-item>
</mat-list>

Respuesta #2

Usa un objeto dinámico para hacer esto, como comment.isVisible. Ahora el objeto isVisible se crea dinámicamente y se modificará su valor al pasar el mouse por encima o retirarlo.

Por favor, intenta de esta manera

<mat-list>
  <mat-list-item *ngFor="let comment of comments" (mouseenter)="comment.isVisible = true" (mouseleave)="comment.isVisible= false" >
    <h4 mat-line >{{comment.text}}</h4>
    <p mat-line style="font-size:x-small; color:rgba(0, 0, 0, 0.54)"> 3 replies </p>
    <mat-icon *ngIf="comment.isVisible">reply</mat-icon>
  </mat-list-item>
</mat-list>