2016-11-23 100 views
1

我有以下代碼:Angular2動態IMG SRC

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

運行我的應用我看到的圖像正確顯示。不過,如果當前路線處於活動狀態,我希望圖像更改。所以我做:

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

這在另一方面結果: enter image description here

什麼我做錯了或這是一個錯誤?

回答

0

我發現了這個問題。這是正確的方法。

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

我用SRC = {{}}代替SRC = {{}}

2

您應該使用不同的Angular 2綁定。

<img>標籤應該是:

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

注意周圍的src屬性的方括號,並引號之間的模板表達式。

一些閱讀有關屬性綁定:https://angular.io/docs/ts/latest/guide/template-syntax.html#!#property-binding

+1

如果綁定的值是一個字符串,它們是等價的。 –

+0

我的方法有什麼不同? – mp3por

+1

@GünterZöchbauer我不知道,但在閱讀https://angular.io/docs/ts/latest/guide/template-syntax.html#interpolation後,我必須同意:) –

0

我有同樣的問題,碰到。我的解決方案對於更改圖像的src有點棘手。
在HTML:

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

在角:

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