Angular svg 匹配组件与 svg 元素

Angular svg matching component with svg elements

考虑以下与 <svg icon="close"></svg> 匹配的组件以显示图标:

@Component({
    selector: 'svg[icon]',
    template: `<use [attr.xlink:href]="'icons.svg#'+icon"></use>`
})
export class SvgIconComponent {
    @Input() icon: string;
}

失败是因为 Angular 找不到 <use> 元素,因为它不知道组件的内容在 <svg> 中。如果 Angular 会注意到 selector 确保了这一点,那就太好了,但事实并非如此。

准确的错误是:

Uncaught Error: Template parse errors:
'use' is not a known element:
    1. If 'use' is an Angular component, then verify that it is part of this module.
    2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. 

显然我可以将 NO_ERRORS_SCHEMA 放在组件的模块上,但我不想这样做,因为模块中还有其他组件,并且因为我希望未知元素错误检查起作用.

那么,我如何告诉 Angular 它应该将这个特定组件的内容视为 SVG 内容?如果那不可能,是否有其他方法可以干净利落地做到这一点?

解决方法其实很简单。只需对组件中的元素使用 svg: 命名空间,如下所示:

<svg:use [attr.xlink:href]="'icons.svg#'+icon"></svg:use>

最后我自己解决了这个问题——我很想知道是否有很好的文档说明为什么以及如何在某处工作。