Blog>
Snippets

Utilizing Animation Metadata for Reusable Animations

Create reusable animation triggers and states using Angular's metadata functions, allowing for flexible application of consistent animations across components.
import { trigger, state, style, animate, transition } from '@angular/animations';

// Function to define reusable animation parameters
function fadeInOutAnimation(duration: string, easing: string) {
  return trigger('fadeInOut', [
    state('in', style({ opacity: 1 })),
    state('out', style({ opacity: 0 })),
    transition('out => in', animate(`${duration} ${easing}`)),
    transition('in => out', animate(`${duration} ${easing}`)),
  ]);
}

// Usage in a component
@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css'],
  animations: [ fadeInOutAnimation('300ms', 'ease-in-out') ]
})
export class ExampleComponent {
  // Component logic goes here
}
This code snippet defines a reusable animation trigger 'fadeInOut' using the Angular animation metadata functions. The 'fadeInOutAnimation' function generates a trigger with two states: 'in' and 'out', and transitions between these states with customizable duration and easing. The function is then used in a component's metadata to apply it.