Enter and leave animations make elements appear and disappear smoothly. They help users notice changes on the page without sudden jumps.
Enter and leave animations in Angular
import { trigger, transition, style, animate } from '@angular/animations'; @Component({ selector: 'app-example', templateUrl: './example.component.html', animations: [ trigger('fadeInOut', [ transition(':enter', [ style({ opacity: 0 }), animate('300ms ease-in', style({ opacity: 1 })) ]), transition(':leave', [ animate('300ms ease-out', style({ opacity: 0 })) ]) ]) ] }) export class ExampleComponent {}
:enter means when the element is added to the DOM.
:leave means when the element is removed from the DOM.
trigger('slideInOut', [ transition(':enter', [ style({ transform: 'translateX(-100%)' }), animate('400ms ease-out', style({ transform: 'translateX(0)' })) ]), transition(':leave', [ animate('400ms ease-in', style({ transform: 'translateX(100%)' })) ]) ])
trigger('growShrink', [ transition(':enter', [ style({ transform: 'scale(0)' }), animate('200ms ease-out', style({ transform: 'scale(1)' })) ]), transition(':leave', [ animate('200ms ease-in', style({ transform: 'scale(0)' })) ]) ])
This Angular component shows a green box that fades in when you click the button and fades out when you click again. The @fadeInOut animation triggers on the box's enter and leave events.
The button toggles the box's visibility using *ngIf. The animation smoothly changes the box's opacity.
ARIA live region aria-live="polite" helps screen readers announce the box's appearance.
import { Component } from '@angular/core'; import { trigger, transition, style, animate } from '@angular/animations'; @Component({ selector: 'app-fade-example', template: ` <button (click)="show = !show">Toggle Box</button> <div *ngIf="show" @fadeInOut class="box" aria-live="polite"> Hello! I fade in and out. </div> `, styles: [ `.box { width: 200px; height: 100px; background-color: #4caf50; color: white; display: flex; align-items: center; justify-content: center; margin-top: 1rem; border-radius: 0.5rem; }` ], animations: [ trigger('fadeInOut', [ transition(':enter', [ style({ opacity: 0 }), animate('500ms ease-in', style({ opacity: 1 })) ]), transition(':leave', [ animate('500ms ease-out', style({ opacity: 0 })) ]) ]) ] }) export class FadeExampleComponent { show = false; }
Always use *ngIf or structural directives to trigger enter and leave animations.
Use aria-live attributes to improve accessibility for dynamic content.
Test animations on different devices to ensure smooth performance.
Enter and leave animations make elements appear and disappear smoothly.
Use :enter and :leave in Angular animations to define these effects.
Animations improve user experience by showing changes gently and accessibly.