Angular2 - NgFor with SVG

时间:2017-04-24 19:09:35

标签: angular typescript svg

我有一个SVG元素,我想用ngFor绘制。 SVG只由线组成,所以理论上它应该是可能的。 我目前有以下代码:

MY-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>

它不起作用,我确信我有多个语法错误,但我不确切地知道哪些错误。

2 个答案:

答案 0 :(得分:5)

你不应该混合绑定和插值。试试这个:

<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>

并将组件中的:更改为=

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 }
  ];
}

答案 1 :(得分:2)

只是一个建议

另一个解决方案是使用ngx-svg module,这将允许轻松生成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对象旁边,您还可以使用此库创建不同的对象(椭圆,矩形,折线,多边形等)。

相关问题