Home > OS >  How to set image with binding for onMouseOut on Angular button
How to set image with binding for onMouseOut on Angular button

Time:03-03

I need a button in Angular. For this button I will set a image (icon) by binding. On hover the image should change. On event onm ouseOut it should set back to the binded image.

Using the event onm ouseOut I get the error

NG8002: Can't bind to 'onMouseOut' since it isn't a known property of 'input'.

I tried

  • <button src='...
  • <button ..><img ...
  • <input type="image" ...

and get allways the same error.

How can I use the onm ouseOut with binding on a angular button.

<input type="image" onclick="onUp()" 
src="/assets/icons/{{imgUp}}.png" 
onMouseOver="this.src='/assets/icons/up-hover.png'" 
onMouseOut="this.src='/assets/icons/{{imgUp}}.png'" />

CodePudding user response:

Create a element reference like i have created imgElem below and use it.

<input
  #imgElem
  type="image"
  onclick="onUp()"
  src="/assets/icons/{{ imgUp }}.png"
  (mouseenter)="imgElem.src = '/assets/icons/up-hover.png'"
  (mouseleave)="imgElem.src = '/assets/icons/{{imgUp}}.png'"
/>

CodePudding user response:

My solution is setting the image allways with Typescript:

<input type="image" [src]="imgPathUp" (click)="onUp()" 
(mouseenter)="onUpHover()"  (mouseleave)="onUpLeave()" />

  imgUpNeutral = '/assets/icons/up.png';
  imgUpHover = '/assets/icons/up-hover.png';
  imgUpActive = '/assets/icons/up-active.png';
  imgPathUp = this.imgUpNeutral;
  currentImgUp = this.imgPathUp;
  
  
  public onUpHover(): void {
    this.imgPathUp = this.imgUpHover;
  }

  public onUpLeave(): void {
    this.imgPathUp = this.currentImgUp;
  }
  
  public onUp(): void {
    if (this.vote === VoteEnum.neutral) { // use the logic you need
      this.vote = VoteEnum.up;
      this.imgPathUp = this.imgUpActive;
    } else {
      this.vote = VoteEnum.neutral;
      this.imgPathUp = this.imgUpNeutral;
    };
    this.currentImgUp = this.imgPathUp;
  }

  • Related