Blog>
Snippets

SVG Path Binding in Angular

Provide an example of how to bind an SVG `path` element's `d` attribute to a property in the Angular component to dynamically generate paths such as charts or diagrams.
import { Component } from '@angular/core';

@Component({
  selector: 'app-svg-path-example',
  template: `
    <svg width="200" height="200">
      <path [attr.d]="pathD" stroke="blue" fill="none"/>
    </svg>
  `
})
export class SvgPathExampleComponent {
  pathD = 'M10 10 H 90 V 90 H 10 L 10 10';
}
This is the Angular component containing the SVG path element. The path's `d` attribute is bound to a property of the component named `pathD`. The property holds a string with SVG path commands to draw a square within the SVG element.
@Component({
  // component's metadata including the selector and the template
})
export class AppComponent implements OnInit {
  dynamicPath: string;

  ngOnInit() {
    this.generateDynamicPath();
  }

  generateDynamicPath() {
    // Logic to dynamically generate the SVG path
    this.dynamicPath = '...'; // Update the SVG path string here
  }
}
In this Angular component, we define a property named `dynamicPath` that will hold our path data string. In the `ngOnInit` lifecycle hook, we call a method `generateDynamicPath` that is responsible for generating the SVG path data. The `generateDynamicPath` method might contain any logic necessary to create a string that represents SVG path commands.
<svg width="200" height="200">
  <path [attr.d]="dynamicPath" stroke="green" fill="none"></path>
</svg>
The SVG element within the Angular component's template. The path element's `d` attribute is dynamically bound to the `dynamicPath` property of the component using Angular's property binding syntax `[attr.d]`. The path is styled with a stroke and no fill.