[英]Angular2 - NgFor with SVG
我有一个SVG元素,我想用ngFor绘制。 SVG只由线组成,所以理论上它应该是可能的。 我目前有以下代码:
我-component.js:
import {Component} from 'angular2/core';
@Component({
selector: 'my-component',
templateUrl: 'my-component.html'
})
export class MyComponent{
lines: [
{ weight: 0.4, x1: 86.69, y1: 1, x2: 98.91, y2: 1 },
{ weight: 0.5, x1: 85.31, y1: 9.67, x2: 98.23, y2: 9.67 }
]
}
我-组件的HTML:
<svg id="lines" viewBox="0 0 320.6 542.59" *ngFor='line of lines'>
<line class="line" [attr.x1]="{{ x1 }}" [attr.y1]="{{ y1 }}" [attr.x2]="{{ x2 }}" [attr.y2]="{{ y2 }}"/>
</svg>
它不起作用,我确信我有多个语法错误,但我不确切知道哪些错误。
你不应该混合绑定和插值。 尝试这个:
<svg id="lines" viewBox="0 0 320.6 542.59" >
<line *ngFor="let line of lines" class="line" [attr.x1]="line.x1" [attr.y1]="line.y1" [attr.x2]="line.x2" [attr.y2]="line.y2"/>
</svg>
并在组件中更改:
to =
export class MyComponent{
lines = [ // here
{ weight: 0.4, x1: 86.69, y1: 1, x2: 98.91, y2: 1 },
{ weight: 0.5, x1: 85.31, y1: 9.67, x2: 98.23, y2: 9.67 }
];
}
只是一个建议
另一种解决方案是使用ngx-svg模块 ,它可以轻松生成SVG对象。 要重现上面的代码,您必须包含该模块,然后在您可以使用的视图中 -
<svg-container containerId="lineContainer">
<svg-line *ngFor="let line of lines" [borderSize]="line.weight" [x0]="line.x1" [y0]="line.y1" [x1]="line.x2" [y2]="line.y2"></svg-line>
</svg-container>
除了上述参数,您还可以侦听多个事件,如onClick,onMouseOver,onMouseOut,onDoubleClick,并传递边框颜色变量。
在线svg对象旁边,您还可以使用此库创建不同的对象(椭圆,矩形,折线,多边形等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.