Angular 2:将* ngIf添加到SVG会引发错误 [英] Angular 2: adding *ngIf to SVG throws an error

查看:160
本文介绍了Angular 2:将* ngIf添加到SVG会引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的一个组件的SVG(它将是另一个svg的子对象):

This is my SVG of a component (which will be a child another svg):

<svg *ngIf="complete" [attr.width]="width" [attr.height]="height" viewBox="0 0 180 100" version="1.1" xml:space="preserve" style="overflow:visible;stroke-linejoin:round;stroke-miterlimit:1.41421;"> ...</svg>

使用SVG*ngIf添加到组件模板时出现错误:

I'm getting an error when adding *ngIf to a component template with SVG:

未处理的承诺拒绝:模板解析错误:无法绑定到 'ngIf',因为它不是':svg:svg'的已知属性.

Unhandled Promise rejection: Template parse errors: Can't bind to 'ngIf' since it isn't a known property of ':svg:svg'.

*ngIf在代码的其他部分工作正常,除了svg

*ngIf works fine on other parts of the code except for svg

HeightWidth属性绑定可以正常工作.

Height and Width attributes binding works fine.

我检查了ngIf拼写和模型属性. 我测试了添加BrowserModule,没有任何区别. 我在@NgModule进口中有CommonModule.

I have checked ngIf spelling and model property. I tested adding BrowserModule, didn't make any difference. I have CommonModule in @NgModule imports.

具有SVG的组件是由componentFactory生成的.

The component that have the SVG is generated by componentFactory.

我有Angular 2 Universal(最新版​​本)

I have Angular 2 Universal (latest version)

推荐答案

使用Angular和SVG设置动态绑定需要在属性之前添加attr前缀.

Setting up dynamic bindings using Angular and SVG requires that you add the attr prefix before the attribute.

由于* ngIf是[ngIf]的语法糖,我通过写出ngIf和ng-template来解决错误消息:

Because *ngIf is syntatic sugar for [ngIf], I've gotten around the error message by writing out the ngIf and the ng-template:

<ng-template [ngIf]="!label.hasCompensation">
        <svg:text text-anchor="middle" [attr.x]="label.x" [attr.y]="label.y">
                {{label.encoder}} |
                <tspan style="fill:red">{{label.compensation}}</tspan>
        </svg:text>
</ng-template>

主要原因是SVG DOM通常不像HTML DOM那样公开属性.

The primary reason for this is that the SVG DOM generally does not expose attributes as properties like the HTML DOM does.

作为参考,Tero Parviainen写了出色的在他的博客上发布.

For reference, Tero Parviainen has written an excellent post on his blog.

这篇关于Angular 2:将* ngIf添加到SVG会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆