Blog>
Snippets

Animation Callbacks and State Management

Manage complex animation states and synchronize with application data using animation callbacks (start and done events) within Angular component methods.
import { Component } from '@angular/core';
import { animate, state, style, transition, trigger } from '@angular/animations';

@Component({
  selector: 'app-animation-example',
  templateUrl: './animation-example.component.html',
  styleUrls: ['./animation-example.component.css'],
  animations: [
    trigger('openClose', [
      state('open', style({
        height: '200px',
        opacity: 1,
        backgroundColor: 'yellow'
      })),
      state('closed', style({
        height: '100px',
        opacity: 0.5,
        backgroundColor: 'green'
      })),
      transition('open => closed', [
        animate('1s')
      ]),
      transition('closed => open', [
        animate('0.5s')
      ]),
    ]),
  ]
})
export class AnimationExampleComponent {
  isOpen = true;

  toggle() {
    this.isOpen = !this.isOpen;
  }

  animationStarted(event: AnimationEvent) {
    console.log('Animation started', event);
  }

  animationDone(event: AnimationEvent) {
    console.log('Animation done', event);
  }
}
This Angular component sets up an animation for an open/close state with appropriate styles. It also defines methods to toggle the state and handle animation start/done events.