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?

3 Answers 3

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">
Sign up to request clarification or add additional context in comments.

3 Comments

I was wondering if there is any way to access the img src attribute without declaring a new variable
is it possible to change img src using reference on change event of radio button in Angular2 not in .ts file? @Piyush
@Piyush.kapoor what if img tag in ngFor and I need get image from server by passing name of the file
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';
}

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.