Blog>
Snippets

Angular SVG Animations on Data Change

Illustrate how to trigger SVG animations in an Angular application when data changes occur by utilizing Angular's animation library to manipulate the SVG elements.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'app-svg-animated-component',
  template: `<!-- SVG element with animation trigger -->
  <svg width="100" height="100">
    <circle [@circleAnimation]='circleRadius' cx="50" cy="50"/>
  </svg>`,
  animations: [
    trigger('circleAnimation', [
      state('small', style({
        r: '10'
      })),
      state('large', style({
        r: '40'
      })),
      transition('small <=> large', animate('500ms ease-in-out'))
    ])
  ]
})
export class SvgAnimatedComponent implements OnChanges {
  @Input() data: number;
  circleRadius: string = 'small';

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['data']) {
      this.circleRadius = this.data > 20 ? 'large' : 'small';
    }
  }
}
Angular component that includes an SVG circle with a radius that changes size based on the input data. The animation is achieved by defining triggers with different states and transitions.