Its really simple script. First assign image source URL to variable imgSrc. Use mouseover and mouseout event to change the variable values.

Markup

Here src attribute is bound with imgSrc variable. 
<img [src]="imgSrc" (mouseover)="onMouseOver()" (mouseout)="onMouseOut()"/>

Script

Whenever user mouse over on the image onMouseOver function will be called and new image will be displayed. This will be reset when user takes mouse out of that image
import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `
  <h2>Change Image Source On Mouse Over Using Angular 2</h2>
  <div>
    <img [src]="imgSrc" (mouseover)="onMouseOver()" (mouseout)="onMouseOut()"/>
  </div>
  `
})
export class AppComponent {
  imgSrc: string = "../css/assets/twitter_brown.png";

  onMouseOver(): void {
    this.imgSrc = "../css/assets/twitter_blue.png";
  }

  onMouseOut(): void {
    this.imgSrc = "../css/assets/twitter_brown.png";
  }
}

3 comments:

Blogroll

Follow this blog by Email

Popular Posts