Angular provides its own incredibly powerful, deeply integrated animation module.
Instead of relying heavily on messy CSS files, you can define sophisticated animation choreographies directly in your TypeScript components.
This enables animations that react dynamically to component data and lifecycle events!
To use animations, you must first enable the module in your application bootstrap configuration.
If you are using standalone components, import provideAnimations() in your main.ts file.
Once provided, you can import animation functions like trigger, state, and transition from @angular/animations.
Animations in Angular are defined using "Triggers".
Inside a trigger, you define "States" (like open or closed) and the exact CSS styles associated with those states.
You then define "Transitions", which dictate how the element animates as it moves between those states.
import { Component } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'app-box',
template: '<div [@openClose]="isOpen ? open : closed"></div>',
animations: [
trigger('openClose', [
state('open', style({ height: '200px', opacity: 1, backgroundColor: 'green' })),
state('closed', style({ height: '100px', opacity: 0.5, backgroundColor: 'red' })),
// Animates state changes smoothly over 1 second
transition('open => closed', [ animate('1s') ]),
transition('closed => open', [ animate('0.5s') ]),
])
]
})
export class BoxComponent {
isOpen = true;
}
One of the hardest things to animate in standard CSS is an element physically entering or leaving the DOM (like *ngIf).
Angular provides special transition aliases specifically for this: :enter and :leave.
You can use these to gracefully fade elements in when they are created, and fade them out before they are destroyed!
animations: [
trigger('fadeAnimation', [
// When the element is created by *ngIf
transition(':enter', [
style({ opacity: 0 }),
animate('500ms', style({ opacity: 1 }))
]),
// When the element is destroyed by *ngIf
transition(':leave', [
animate('500ms', style({ opacity: 0 }))
])
])
]
Where do you typically define your animation triggers and states in an Angular application?
Which transition alias should you use to animate an element exactly when it is added to the DOM via *ngIf?