13

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?

TheUnreal
  • 23,434
  • 46
  • 157
  • 277

3 Answers3

16

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">
Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21
3

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';
}
Rahul Kumar
  • 5,120
  • 5
  • 33
  • 44
  • 1
    This is not correct. With #image you get an ElementRef object, not a direct access to the DOM object ... but of course, the ElementRef has a "nativeElement" property as an accessor to the DOM object. So, it would be: image.nativeElement.src = "path to new image"; – flackjap Jun 28 '17 at 21:07
3

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">