mp3por
mp3por

Reputation: 1852

Angular2 dynamic img src

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 ?

Upvotes: 13

Views: 23291

Answers (4)

Daniel Jacobson
Daniel Jacobson

Reputation: 171

I was able to solve it by doing a unary 'IF' in nested form

    <td class="cent">
         <img  [src]="OrdersFund?.status=='P' ? 'assets/P.png' : OrdersFund?.status=='E' ? 'assets/E.png' : 'assets/C.png'" /> 
    </td>

Upvotes: 2

mp3por
mp3por

Reputation: 1852

I found the problem. This is the correct way.

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

I was using src={{}} instead of src="{{}}".

Upvotes: 1

David M.
David M.

Reputation: 2640

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

Upvotes: 13

Afsun Khammadli
Afsun Khammadli

Reputation: 2068

I came across with same problem. My solution is a bit tricky to change src of image.
In html:

<div id="imageDiv"></div>

In angular:

document.getElementById('imageDiv').innerHTML = '<img src="' + YourPhotoURLOrBase64String + '"/>';

Upvotes: 1

Related Questions