当它在组件内部时,如何动态地将类和路径添加到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]'
在该代码中,当我从{{iconId}}
中删除<svg class="another-class {{iconId}}">
时没有错误,但svg图标也没有显示。
这适用于Angular 6:
<svg [ngClass]="'another-class ' + iconId">
<use [attr.xlink:href]="'/icon-path/def.svg#' + iconId"></use>
</svg>
使用ngClass
[ngClass]="iconId"
[ngClass]="iconId ? iconId : ''"
[attr.xlink:href]="'/icon-path/def.svg#' + iconId"
在AppModule中导入它。我记得它在Angular2中为我修复但在Angular4中不知道。
import { CommonModule } from '@angular/common';