Blog>
Snippets

Multi-Element Animation Coordination

Coordinate animations across multiple elements using Angular's query and stagger functions, ensuring a smooth, choreographed animation flow.
import { trigger, transition, query, style, animate, stagger } from '@angular/animations';

export const cardAnimation = trigger('cardAnimation', [
  // Trigger name is 'cardAnimation'
  transition('* => *', [ // This transition will apply to any change in the state
    query(':enter', [ // Select all entering elements
      style({ opacity: 0 }), // Initial style for entering elements
      stagger('100ms', [ // Stagger the animations by 100ms intervals
        animate('0.5s ease-out', style({ opacity: 1 })) // Animate to an opacity of 1 over 0.5 seconds
      ])
    ], { optional: true }) // Query is optional in case there are no entering elements
  ])
]);
This Angular animation code defines a trigger named 'cardAnimation' that coordinates the entry (or appearance) of multiple elements smoothly with a staggered effect. When elements enter the DOM, they will initially be invisible (opacity 0) and will gradually fade in to full visibility (opacity 1), with each element's animation starting 100 milliseconds apart.
@Component({
  selector: 'app-card-component',
  templateUrl: './card-component.html',
  styleUrls: ['./card-component.css'],
  animations: [cardAnimation] // Include the defined animation in the component's metadata
})
export class CardComponent {
  // Your component logic goes here
}
This code snippet is the decorator for an Angular component called 'CardComponent'. It sets up the component's selector, HTML template, stylesheet, and includes the 'cardAnimation' trigger within the animations property. This sets up the 'CardComponent' to use the defined coordinated animations.
<div [@cardAnimation]="cards.length">
  <div *ngFor="let card of cards">
    <!-- Card markup goes here -->
  </div>
</div>
In this snippet, Angular's structural directive *ngFor is used within a div element to render a list of 'cards'. The 'cardAnimation' trigger is applied to the parent div, which controls the staggered animation of each card as it enters the DOM, with the number of cards dynamically determining the animation state.