Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 dynamic img src

Tags:

angular

I have the following code:

<a routerLink="/dashboard" routerLinkActive="active" #rla="routerLinkActive">
          <img src="/assets/navigation/dashboard-icon-active.svg" />
        <template [ngIf]="!isSmallSidebar">
          Dashboard
        </template>
      </a>

Running my app I see the image displayed correctly. However I want the image to change if the current route is active. So I did:

<a routerLink="/dashboard" routerLinkActive="active" #rla="routerLinkActive">
        <!-- <img
          id="re-nav-dashboard-img"
          src={{ rla.isActive ? './assets/navigation/dashboard-icon-active.svg' : './assets/navigation/dashboard-icon.svg' }} /> -->
        <template [ngIf]="!isSmallSidebar">
          Dashboard
        </template>
      </a>

This on the other hand results in: enter image description here

What am I doing wrong or is this a bug ?

like image 619
mp3por Avatar asked Nov 23 '16 12:11

mp3por


1 Answers

You should use Angular 2 bindings differently.

Your <img> tag should be:

<img id="re-nav-dashboard-img" [src]="rla.isActive ? './assets/navigation/dashboard-icon-active.svg' : './assets/navigation/dashboard-icon.svg'" />

Notice the square brackets around the src attribute, and the template expression between the quotes.

Some reading about property bindings: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#property-binding

like image 78
David M. Avatar answered Oct 22 '22 10:10

David M.