Search code examples
angulartypescriptmouseeventmouseenter

How to show one element on mouse-enter - Angular 4+


I have a form which needs to show a cancel icon on mouse enter to the relevant element. But on mouse enter , all the cancel icons are visible. I have referred similar questions but those didn't solve my issue. Here are the code segments

.html

 <div *ngFor='let tool of dropzone; let i=index' (mouseenter)="showIcon(i)" (mouseleave)="hideIcon(i)">
            <label>{{tool}}  </label></td>          
            <mat-icon (click)="cancel(tool,i)">
              <div *ngIf="isHovering">cancel </div>            
            </mat-icon>
 </div>

component.ts

showIcon(tool) {
    this.isHovering = true;
    console.log(tool)
  }
  hideIcon() {
    this.isHovering = false;
  }

How can i display only the relevant element's cancel icon on mouse enter?


Solution

  • Issue

    The issue is with the isHovering. You are using the same variable for all.

    Solution

    If you don't want to touch the existing variable dropzone then you can create separate object to hold the status of each icons. Refer the below implementation

    ts

    iconsState = { };
    
    showIcon(index) {
        this.iconsState[index] = true;
      }
      hideIcon() {
        this.iconsState[index] = false;
      }
    

    html

        <div *ngFor='let tool of dropzone; let i=index' (mouseenter)="showIcon(i)" (mouseleave)="hideIcon(i)">
                        <label>{{tool}}  </label></td>          
                        <mat-icon (click)="cancel(tool,i)">
                          <div *ngIf="iconsState[i]">cancel </div>            
                        </mat-icon>
       </div>