Triggers and states help manage changes and actions in your app smoothly. They make your app respond to user actions or data changes with animations or style changes.
0
0
Trigger and state definitions in Angular
Introduction
When you want to animate a button when clicked.
When you want to show or hide a menu with a smooth transition.
When you want to change the style of an element based on user interaction.
When you want to animate a list item entering or leaving the screen.
When you want to create visual feedback for form input focus.
Syntax
Angular
trigger('triggerName', [ state('stateName', style({ /* CSS styles */ })), transition('state1 => state2', [ animate('duration easing', style({ /* CSS styles */ })) ]) ])
trigger defines the animation with a name you use in your template.
state defines how the element looks in a certain state.
Examples
This example defines two states: 'open' and 'closed'. The element changes height and opacity with a smooth animation when toggling between states.
Angular
trigger('openClose', [ state('open', style({ height: '200px', opacity: 1 })), state('closed', style({ height: '100px', opacity: 0.5 })), transition('open <=> closed', [animate('0.5s ease-in-out')]) ])
This example animates an element fading in when it appears and fading out when it disappears.
Angular
trigger('fadeInOut', [ state('in', style({ opacity: 1 })), transition(':enter', [ style({ opacity: 0 }), animate('300ms ease-in') ]), transition(':leave', [ animate('300ms ease-out', style({ opacity: 0 })) ]) ])
Sample Program
This Angular component shows a button and a box. Clicking the button toggles the box between 'open' and 'closed' states. The box changes height and opacity smoothly using the defined trigger and states.
Angular
import { Component } from '@angular/core'; import { trigger, state, style, transition, animate } from '@angular/animations'; @Component({ selector: 'app-toggle-box', template: ` <button (click)="isOpen = !isOpen">Toggle</button> <div [@openClose]="isOpen ? 'open' : 'closed'" class="box"> I change size and opacity! </div> `, styles: [ `.box { width: 200px; background-color: lightblue; margin-top: 10px; overflow: hidden; }` ], animations: [ trigger('openClose', [ state('open', style({ height: '200px', opacity: 1 })), state('closed', style({ height: '100px', opacity: 0.5 })), transition('open <=> closed', [animate('0.5s ease-in-out')]) ]) ] }) export class ToggleBoxComponent { isOpen = true; }
OutputSuccess
Important Notes
Use simple CSS styles inside style() to define how states look.
Transitions define how to animate between states, including timing and easing.
Use the trigger name in your template with [@triggerName] to connect animations.
Summary
Triggers group states and transitions for animations.
States define how elements look in different conditions.
Transitions animate changes between states smoothly.