问题描述
这是我的一个组件的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
*ngIf
works fine on other parts of the code except for svg
Height
和Width
属性绑定可以正常工作.
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会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!