Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 change image src attribute

Tags:

angular

Assuming I have the following code:

<img [src]="JwtService.characterImage(enemy)" 
        class="{{enemy.status}}"
    (click)="sidenav.toggle();" style="cursor:pointer">

How I can change this img src asttribute from my components .ts file?

like image 865
TheUnreal Avatar asked Jul 12 '16 16:07

TheUnreal


3 Answers

You could pass a reference of your tag using $event and change it's attribute from your typescript code.

<img (click)="functionInTypeScript($event.target)">

Or if you want to change something in image tag on another event you could do it like this

<img #image>
<button (click)=functionInTypeScript(image)>

and then simply access in typescript code like this

functioninTypeScript(image:any) {
   image.src='path to new image';
}
like image 195
Rahul Kumar Avatar answered Oct 27 '22 14:10

Rahul Kumar


Typescript:

getImage(image: any, time: string) {
    const t1 = '06:00';
    const t2 = '18:00';
    if (time >= t1 && time < t2) {
      return ('/images/morning.png');
    } else {
      return ('/images/evening.png');
    }
  }

HTML :

  <img [src]="getImage(this,bettrainList.departureTime)" width="25">
like image 22
Vishnu Kant Avatar answered Oct 27 '22 13:10

Vishnu Kant


Add a imgSrc in your component

class Component {
 constructor(jwtService: JwtService) {
     this.imgSrc = JwtService.characterImage(enemy);
 }
}

<img [src]="imgSrc" 
        class="{{enemy.status}}"
    (click)="sidenav.toggle();" style="cursor:pointer">
like image 16
Piyush.kapoor Avatar answered Oct 27 '22 12:10

Piyush.kapoor