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

问题描述 投票:0回答:3

当它在组件内部时,如何动态地将类和路径添加到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 svg angular-cli
3个回答
2
投票

这适用于Angular 6:

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

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 [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

© www.soinside.com 2019 - 2024. All rights reserved.