2016-11-23 102 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 + '"/>';