charles Lgn
charles Lgn

Reputation: 528

Call method from HTML only one time in Angular2

I would like to implement img, with src depending on a variable in back. so I have this :
<img src="./image/-ex-{{getImg()}}.png" />

But it calls the function of every screen event. I want that it load the picture at the begin and then it never call the function again

my back :

`getImg() {
    return this.iso === '0' ? 'a' :
           this.iso === '1' ? 'b' :
           this.iso === '2' ? 'c' :'d';
  }`

Upvotes: 0

Views: 6426

Answers (4)

Divyang Patel
Divyang Patel

Reputation: 1

If you are working with dynamic data, the best approach would be to use a pipe. Here is an example

import { Pipe, PipeTransform } from '@angular/core';
    
@Pipe({
  name: 'imgSrc'
})
export class ImgSrcPipe implements PipeTransform {
    
transform(value : any): string {
  return value === '0' ? 'a' :
         value === '1' ? 'b' :
         value === '2' ? 'c' :'d';
  }
    
}

Upvotes: 0

Padmapriya Vishnuvardhan
Padmapriya Vishnuvardhan

Reputation: 2166

Instead of src="./image/-ex-{{getImg()}}.png", src="./image/-ex-{{iso}}.png" and get the value of this.iso in the constructor or ngInit.

This will avoid calling the function multiple times.

Upvotes: 1

Gianluca Paris
Gianluca Paris

Reputation: 1429

Just declare a variable, e.g. private imgUrl: string; then in your ngOnInit() or constructor() call this.imgUrl = getImg() and in your HTML <img src="./image/-ex-{{imgUrl}}.png" />

Upvotes: 4

Anuradha Gunasekara
Anuradha Gunasekara

Reputation: 6983

just use a boolean to verify the method is called before

`getImg() {
    if(this.calledBefore) {
      return;
    }
    this.calledBefore = true;
    return this.iso === '0' ? 'a' :
           this.iso === '1' ? 'b' :
           this.iso === '2' ? 'c' :'d';
  }

Or use a varible to store the image url in the component

constructor() {
   this.imageUrl = this.getImg();
}

`

Upvotes: 0

Related Questions