简体   繁体   English

Angular2 - NgFor with SVG

[英]Angular2 - NgFor with SVG

I have an a SVG Element that I would like to draw with ngFor. 我有一个SVG元素,我想用ngFor绘制。 The SVG only consists of lines, so theoretically it should be possible. SVG只由线组成,所以理论上它应该是可能的。 I currently have the following code: 我目前有以下代码:

my-component.js: 我-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 }
  ]
}

my-component-html: 我-组件的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>

It is not working and I am sure that I have multiple syntax mistakes, but I don't know which ones exactly. 它不起作用,我确信我有多个语法错误,但我不确切知道哪些错误。

You shouldn't mix binding and interpolation. 你不应该混合绑定和插值。 Try this: 尝试这个:

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

And also change : to = in your component 并在组件中更改: 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 }
  ];
}

JUST A SUGGESTION 只是一个建议

Another solution would be to use ngx-svg module , which would allow to generate SVG objects easily. 另一种解决方案是使用ngx-svg模块 ,它可以轻松生成SVG对象。 To reproduce the above code you would have to include the module and then in the view you could use - 要重现上面的代码,您必须包含该模块,然后在您可以使用的视图中 -

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

Additionally to the above parameters you can also listen for multiple events, like onClick, onMouseOver, onMouseOut, onDoubleClick, and pass the border color variable. 除了上述参数,您还可以侦听多个事件,如onClick,onMouseOver,onMouseOut,onDoubleClick,并传递边框颜色变量。

Beside the line svg object, you can create also different objects (ellipse, rectangular, polyline, polygon and more) with this library. 在线svg对象旁边,您还可以使用此库创建不同的对象(椭圆,矩形,折线,多边形等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM