Angular 4 - 在组件内向 svg 添加类和路径?

use*_*282 1 svg angular-cli angular

Angular 4位于组件内时,如何在 SVG 中动态添加类和路径?

在我的组件中,当我将以下代码粘贴到组件模板中时,图标有效;

<svg class="another-class iconId">

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

</svg>
Run Code Online (Sandbox Code Playgroud)

但是当我尝试绑定这样的类时:

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

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

</svg>
Run Code Online (Sandbox Code Playgroud)

我收到错误:

Error: Template parse errors:
Can't bind to ':xlink:href' since it isn't a known property of ':svg:use'
Run Code Online (Sandbox Code Playgroud)

四处搜索后,我发现了将代码更改为以下内容的建议:

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

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

</svg>
Run Code Online (Sandbox Code Playgroud)

有了这个,我得到以下错误:

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

我在这里做错了什么?

编辑:按照 Noodle 的建议尝试以下操作:

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

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

</svg>
Run Code Online (Sandbox Code Playgroud)

仍然收到以下错误:

ERROR TypeError: Cannot assign to read only property 'className' of object '[object SVGSVGElement]'
Run Code Online (Sandbox Code Playgroud)

在该代码中,当我删除{{iconId}}<svg class="another-class {{iconId}}">没有错误,但SVG图标不显示任何。

sai*_*sez 6

这适用于 Angular 6:

<svg [ngClass]="'another-class ' + iconId">
  <use [attr.xlink:href]="'/icon-path/def.svg#' + iconId"></use>
</svg>
Run Code Online (Sandbox Code Playgroud)