2017-09-25 27 views
0

如何在組件內部添加一個類和路徑動態到一個SVG中Angular 4Angular 4 - 向組件內的svg添加類和路徑?

在我的組件中,當我將以下代碼粘貼到組件模板中時,該圖標可以工作;

<svg class="another-class iconId"> 

<use xlink:href="/icon-path/def.svg#iconId"></use> 

</svg> 

但是,當我嘗試綁定像這樣一類:

<svg class="another-class {{iconId}}"> 

<use xlink:href="/icon-path/def.svg#{{iconId}}"></use> 

</svg> 

我得到的錯誤:

Error: Template parse errors: 
Can't bind to ':xlink:href' since it isn't a known property of ':svg:use' 

周圍搜索後,我發現建議代碼改成這樣:

<svg class="another-class {{iconId}}"> 

<svg:use [attr.xlink:href]="/icon-path/def.svg#{{iconId}}"></svg:use> 

</svg> 

隨着臨時工t我收到以下錯誤:

Uncaught (in promise): Error: Template parse errors: 
Parser Error: Got interpolation ({{}}) where expression was expected at column 30 in [/icon-path/def.svg#{{iconId}}] 

我在做什麼錯在這裏?

編輯:嘗試了以下的麪條建議:

<svg class="another-class {{iconId}}"> 

<use [attr.xlink:href]="'/icon-path/def.svg#' + iconId"></use> 

</svg> 

仍收到以下錯誤:

ERROR TypeError: Cannot assign to read only property 'className' of object '[object SVGSVGElement]' 

在該代碼中,當我從<svg class="another-class {{iconId}}">刪除{{iconId}}沒有錯誤,但svg圖標也不顯示。

+0

'[attr.xlink:HREF = 「 '/圖標路徑/ def.svg#' + iconId」'無需添加'{{}}當'使用綁定。 – n00dl3

+0

@ n00dl3嗨。試過了。仍然出現錯誤。我用結果更新了我的答案。 – user3607282

+0

看來你忘了大括號。對於類,只需使用ngClass:'[ngClass] =「iconId」'。 – n00dl3

回答

1

使用ngClass

[ngClass]="iconId" 
[ngClass]="iconId ? iconId : ''" 
[attr.xlink:href]="'/icon-path/def.svg#' + iconId" 

導入這的AppModule。我記得它在Angular2中爲我固定,但在Angular4中不知道。

import { CommonModule }  from '@angular/common'; 
+0

嗨。當我這樣做時,出現以下錯誤:由於它不是':svg:svg'的已知屬性,因此無法綁定到'ngClass'。 – user3607282

+0

@ user3607282做了第二個工作? – ShadowFoOrm

+0

嗨,沒有。爲了得到它的工作,我不得不像這樣改變它:[ngClass] =「iconName?iconName:''」。否則有錯誤說我錯過了冒號。之後,我仍然得到錯誤:無法綁定到'ngClass',因爲它不是':svg:svg'的已知屬性。 – user3607282

0

試試這個:

<svg class="getIconClass(iconId)"> 
    <svg:use [attr.xlink:href]="getIconPath(iconId)"></svg:use> 
</svg> 

創建函數:

getIconPath(iconId) { 
    return '/icon-path/def.svg#' + iconId; 
} 

getIconClass(iconId) { 
    return 'another-class ' + iconId; 
} 

我已修改了現有plunker顯示上述功能的使用

也期待在此有用post

+0

試過了,沒有錯誤,但圖標也沒有顯示。 – user3607282