Blog>
Snippets

Dynamically Changing SVG Attributes in Angular

Showcase how to dynamically update SVG element attributes like color, size, or position in response to user interactions or data changes using Angular property bindings.
import { Component } from '@angular/core';

@Component({
  selector: 'app-dynamic-svg',
  template: `
    <svg height="100" width="100">
      <circle
        [attr.cx]="circleX"
        [attr.cy]="circleY"
        [attr.r]="circleRadius"
        [attr.fill]="circleColor"
      ></circle>
    </svg>
    <button (click)="changeAttributes()">Change Circle Attributes</button>`
})
export class DynamicSvgComponent {
  // Initial SVG circle attributes
  circleX = 50;
  circleY = 50;
  circleRadius = 40;
  circleColor = 'blue';

  changeAttributes() {
    // Update SVG circle attributes
    this.circleX = Math.random() * 100;
    this.circleY = Math.random() * 100;
    this.circleRadius = Math.random() * 50 + 10;
    this.circleColor = '#' + Math.floor(Math.random()*16777215).toString(16);
  }
}
This Angular component uses property bindings to dynamically update the attributes of an SVG circle. Upon clicking the button, the 'changeAttributes' method is invoked, which generates new values for the circle's X and Y coordinates, radius, and color, causing the circle to move and change appearance.