【发布时间】:2018-03-06 10:46:17
【问题描述】:
如何在 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>
我收到以下错误:
Uncaught (in promise): Error: Template parse errors:
Parser Error: Got interpolation ({{}}) where expression was expected at column 30 in [/icon-path/def.svg#{{iconId}}]
我在这里做错了什么?
编辑:按照 Noodle 的建议尝试了以下操作:
<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]="'/icon-path/def.svg#'+iconId"使用绑定时无需添加{{}}。 -
@n00dl3 嗨。试过了。仍然出现错误。我用结果更新了我的答案。
-
看来你忘记带牙套了。对于课程,只需使用 ngClass 代替:
[ngClass]="iconId"。 -
对不起。大括号在我的代码中。我忘了在这里添加它们。添加 ngClass 会引发错误:Can't bind to 'ngClass' because it is not an known property of ':svg:svg'
标签: angular svg angular-cli