Call the function in <img> to define the path to src

I am trying something like this:

<img id="icon" class="cercle icon" src="getIcon({{item.status}})" alt="">

      

Function:

getIcon(status){
    switch (status) {
      case 'Ongoing':
        return '../../../../assets/img/icon/PinPlot.png';
      case 'Signaled':
        return '../../../../assets/img/icon/PinWarning.png';
      case 'Finished':

      default:
        return '../../../../assets/img/icon/Pin red.png';
    }
  }

      

But all I get is not like the image if not found. But no errors or warnings.

Any idea?

+3


source to share


2 answers


Use [src]

:

<img id="icon" class="cercle icon" [src]="getIcon(item.status)" alt="">

      



And also you don't need getIcon({{item.status}})

, but without {{}}

.

+7


source


While the previous usage answer [src]

is what I would recommend, the reason your existing technique is not working is because you are not using interpolation (i.e. {{....}}) correctly.

You have:

<img id="icon" class="cercle icon" src="getIcon({{item.status}})" alt="">

      

when you probably meant:

<img id="icon" class="cercle icon" src="{{ getIcon(item.status) }}" alt="">

      



Explanation:

You can think of it this way. Within your template, anything outside of {{}} is treated as literal strings. These are just things in double curly braces that are considered executable code. So, with your example, because of where you put your curly braces, you end up with the line:

src="getIcon(Ongoing)" 

      

after interpolation because you only include item.status

in your curly braces instead of the whole expression.

+2


source







All Articles