Blog>
Snippets

Staggered Animations with Angular AnimationBuilder

Create a staggered animation sequence for a list of items using Angular's AnimationBuilder, optimizing the performance by using web animations API.
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';
import { AnimationBuilder, style, animate } from '@angular/animations';

@Component({
  selector: 'app-staggered-animation',
  template: `<div #container>
    <div *ngFor="let item of items" class="item">{{ item }}</div>
  </div>`,
  styles: [`.item { opacity: 0; transform: translateY(20px); }`]
})
export class StaggeredAnimationComponent {
  @ViewChild('container', { static: true }) container: ElementRef;
  items = ['Item 1', 'Item 2', 'Item 3'];

  constructor(private builder: AnimationBuilder, private renderer: Renderer2) {}

  ngAfterViewInit() {
    const animation = this.builder.build([
      style({ opacity: 0, transform: 'translateY(20px)' }),
      animate('500ms ease-in', style({ opacity: 1, transform: 'translateY(0)' }))
    ]);

    const elements = this.container.nativeElement.children;
    Array.from(elements).forEach((element, index) => {
      // Delay each animation by 100ms more than the previous one
      const player = animation.create(element);
      player.onDone(() => this.renderer.setStyle(element, 'opacity', '1'));
      setTimeout(() => player.play(), index * 100);
    });
  }
}
This Angular component uses the AnimationBuilder to create a staggered animation for a list of items. Using Renderer2 for manual DOM manipulation optimizes rendering. It sets up the animation sequence in ngAfterViewInit by creating a web animation for each child element with a staggered start time.