Home > Software engineering >  How to show another element with hover in Angular?
How to show another element with hover in Angular?

Time:05-18

This is my demo.

When we hover #image-bg, I want #bg-box-hidden will be display: block.

But I'm losing my way to figure out how to solve the problem

<div >
  <div *ngIf="avatar !== null" >
    <img
      
      [src]="avatar"
      (click)="selectImage.click()"
      hover-
      (mouseover)="onImgMouseover($event)"
      (mouseout)="onImgMouseout($event)"
    />
    <div #show  hover->
      <button >
        <i nz-icon nzType="delete" nzTheme="outline"></i>
      </button>
    </div>
  </div>
</div>

CodePudding user response:

The main problem of your code are

  1. Wrong event name.
  2. The element doesn't rendered so you can't targeted the element.

Here is simple solution for you, It might be other way to implement as well.

Try this one, put on your .ts file of the component.

  onImgMouseover($event): void {
    const box = document.getElementsByClassName('bg-box-hidden')[0];
    box.style.display = 'block';
  }
  
  onImgMouseout($event): void {
    const box = document.getElementsByClassName('bg-box-hidden')[0];
    box.style.display = 'none';
  }

and need modify some on HTML something like

   <div
     
     (mouseenter)="onImgMouseover($event)"
     (mouseleave)="onImgMouseout($event)"
     >
     <div *ngIf="avatar === null" >
       <input
         type="file"
         accept=".png,.jpg"
         (change)="updateImage($event)"
         
         #selectImage
       />
     </div>
     <div *ngIf="avatar !== null" >
       <img
         
         [src]="avatar"
         (click)="selectImage.click()"
         hover-
       />
     </div>
     
     <div #show  hover->
       <button >
         <i nz-icon nzType="delete" nzTheme="outline"></i>
       </button>
       <div >
         <input
           type="file"
           accept=".png,.jpg"
           (change)="updateImage($event)"
           
           #selectImage
         />
       </div>
     </div>
     </div>
  • Related