我有用于呈现SVG图标的组件:

import {Component, Directive} from 'angular2/core';
import {COMMON_DIRECTIVES} from 'angular2/common';

@Component({
  selector: '[icon]',
  directives: [COMMON_DIRECTIVES],
  template: `<svg role="img" class="o-icon o-icon--large">
                <use [xlink:href]="iconHref"></use>
              </svg>{{ innerText }}`
})
export class Icon {
  iconHref: string = 'icons/icons.svg#menu-dashboard';
  innerText: string = 'Dashboard';
}

这会触发错误:

EXCEPTION: Template parse errors:
  Can't bind to 'xlink:href' since it isn't a known native property ("<svg role="img" class="o-icon o-icon--large">
<use [ERROR ->][xlink:href]=iconHref></use>
  </svg>{{ innerText }}"): SvgIcon@1:21

如何设置dynamic xlink:href

推荐答案

SVG元素没有属性,因此大多数情况下都需要属性绑定(另请参见Properties and Attributes in HTML).

对于属性绑定,您需要

<use [attr.xlink:href]="iconHref">

<use attr.xlink:href="{{iconHref}}">

Update

消毒可能会引起问题.

另请参阅

UpdateDomSanitizationService将在RC中重命名为DomSanitizer.6.

Update这应该是固定的

but there is an open issue to supp或t this f或 namespaced attributes https://github.com/angular/angular/pull/6363/files

As w或k-around add an additional

xlink:href=""

Angular可以更新属性,但在添加时存在问题.

If xlink:href is actually a property then your syntax should w或k after the PR was added as well.

Angular相关问答推荐

我使用Ngrx的子集 Select 器不起作用

如何避免使用CSS动画制作的幻灯片中闪烁?

Angular 15:将数据从主零部件传递到辅零部件

AG网格Angular 快捷菜单调用函数

NGX- colored颜色 Select 器安装出错

根据环境变量动态加载Angular templateUrl

Angular *ngIf 表达式中这么多冒号的作用是什么?

如何从2个api获取数据并查看Angular material 表中的数据?

使用 Observable 进行渐进式填充

VSCode / Angular 应用程序未完全启动

无法使用@ngrx/component-store 在其他组件中获取状态更改值

Angular 测试被认为是成功的,即使有错误

为什么 Redux 中的对象应该是不可变的?

全局异常处理

ngx-bootstrap modal:如何从模态中获取返回值?

AOT - Angular 6 - 指令 SomeComponent,预期 0 个参数,但go 有 1 个参数

Angular 2 Material 2 日期 Select 器日期格式

没有 ChildrenOutletContexts 的提供者 (injectionError)

Angular2动态改变CSS属性

在 Angular 2 中对 observable 进行单元测试