【问题标题】:Angular 4 - Adding a class & path to svg inside a component?Angular 4 - 在组件内添加类和路径到 svg?
【发布时间】: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]'

当我从&lt;svg class="another-class {{iconId}}"&gt; 中删除{{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


【解决方案1】:

使用 ngClass

[ngClass]="iconId"
[ngClass]="iconId ? iconId : ''"
[attr.xlink:href]="'/icon-path/def.svg#' + iconId"

在 AppModule 中导入它。我记得它在 Angular2 中为我修复,但在 Angular4 中不知道。

import { CommonModule }       from '@angular/common';

【讨论】:

  • 嗨。执行此操作时出现以下错误:无法绑定到 'ngClass',因为它不是 ':svg:svg' 的已知属性。
  • 您好。为了让它工作,我必须像这样改变它:[ngClass]="iconName ? iconName : ''"。否则会出现错误,提示我缺少冒号。之后我仍然得到错误:无法绑定到'ngClass',因为它不是':svg:svg'的已知属性
  • 我有时遇到同样的问题,不记得我是如何解决的。找到修复后我会回来的。
  • 谢谢!!我整天都在为此苦苦挣扎:(
  • 检查 import { CommonModule } from '@angular/common';
【解决方案2】:

试试这个:

<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

【讨论】:

  • 试过了。没有错误,但图标也不显示。
【解决方案3】:

这适用于 Angular 6:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2020-01-15
    • 2014-10-20
    • 1970-01-01
    • 2018-04-24
    相关资源
    最近更新 更多