Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - NgFor with SVG

I have an a SVG Element that I would like to draw with ngFor. The SVG only consists of lines, so theoretically it should be possible. I currently have the following code:

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

my-component-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.

like image 467
IIMaxII Avatar asked Sep 11 '26 15:09

IIMaxII


2 Answers

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

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 }
  ];
}
like image 134
yurzui Avatar answered Sep 13 '26 19:09

yurzui


JUST A SUGGESTION

Another solution would be to use ngx-svg module, which would allow to generate SVG objects easily. 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.

Beside the line svg object, you can create also different objects (ellipse, rectangular, polyline, polygon and more) with this library.

like image 30
Vdas Dorls Avatar answered Sep 13 '26 18:09

Vdas Dorls