Blog>
Snippets

Interactive SVG Graphs in Angular

Demonstrate how to build interactive SVG graphs in Angular by binding data to SVG elements and updating them with animations when the data changes.
import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-svg-graph',
  template: `
    <svg width="300" height="200">
      <rect *ngFor="let bar of bars" [attr.x]="bar.x" [attr.y]="bar.y" width="50" [attr.height]="bar.height" [attr.fill]="bar.color"></rect>
    </svg>
  `
})
export class SvgGraphComponent implements OnInit, OnChanges {
  @Input() graphData: any[];
  bars: any[] = [];

  constructor() { }

  ngOnInit(): void {
    this.updateGraph();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if ('graphData' in changes) {
      this.updateGraph();
    }
  }

  updateGraph(): void {
    // Assuming that graphData is an array of { value: number, color: string }
    // Transform data to SVG friendly format
    this.bars = this.graphData.map((data, index) => ({
      x: index * 60,
      y: 200 - data.value * 2, // Assume max value is 100
      height: data.value * 2,
      color: data.color
    }));
  }
}
Defines an Angular component that creates a simple bar graph using SVG rectangles. It has an input property for data, and it recalculates the bar positions and dimensions whenever the data changes.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { SvgGraphComponent } from './svg-graph.component';

@NgModule({
  declarations: [
    AppComponent,
    SvgGraphComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Sets up an Angular module that declares the AppComponent and SvgGraphComponent, making the latter available to be used in the application.
<app-svg-graph [graphData]="data"></app-svg-graph>
An example usage of the SvgGraphComponent within an Angular template. The 'data' property is bound to the graphData input of the SvgGraph component, so any changes to 'data' will be reflected in the graph.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div>
      <button (click)="changeData()">Change Data</button>
      <app-svg-graph [graphData]="data"></app-svg-graph>
    </div>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  data = [
    { value: 70, color: 'red' },
    { value: 85, color: 'green' },
    { value: 40, color: 'blue' }
  ];

  changeData() {
    // Randomly change data for demonstration
    this.data = this.data.map(d => ({
      value: Math.floor(Math.random() * 100),
      color: d.color
    }));
  }
}
AppComponent code example where the 'data' property is initialized with some sample values and a method 'changeData' to randomly update the data. A button is provided to trigger the data change.