如何在組件內部添加一個類和路徑動態到一個SVG中Angular 4?Angular 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圖標也不顯示。
'[attr.xlink:HREF = 「 '/圖標路徑/ def.svg#' + iconId」'無需添加'{{}}當'使用綁定。 – n00dl3
@ n00dl3嗨。試過了。仍然出現錯誤。我用結果更新了我的答案。 – user3607282
看來你忘了大括號。對於類,只需使用ngClass:'[ngClass] =「iconId」'。 – n00dl3