Performance: Transition between states
This affects how smoothly the UI updates when components change state, impacting user interaction responsiveness and visual stability.
Jump into concepts and practice - no test required
import { Component } from '@angular/core'; import { trigger, state, style, animate, transition } from '@angular/animations'; @Component({ selector: 'app-good-transition', template: `<div [@fadeInOut]="isVisible ? 'visible' : 'hidden'" (click)="toggle()">Content</div>`, animations: [ trigger('fadeInOut', [ state('visible', style({ opacity: 1 })), state('hidden', style({ opacity: 0 })), transition('visible <=> hidden', animate('300ms ease-in-out')) ]) ] }) export class GoodTransitionComponent { isVisible = true; toggle() { this.isVisible = !this.isVisible; } }
import { Component } from '@angular/core'; @Component({ selector: 'app-bad-transition', template: `<div [style.opacity]="isVisible ? '1' : '0'" (click)="toggle()">Content</div>`, }) export class BadTransitionComponent { isVisible = true; toggle() { this.isVisible = !this.isVisible; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct style changes on state toggle | Minimal DOM ops | Multiple reflows per toggle | High paint cost due to layout changes | [X] Bad |
| Angular animations with opacity transitions | Minimal DOM ops | No reflows, only composite | Low paint cost, GPU accelerated | [OK] Good |
transition in Angular animations?trigger, state, and transition to control animations.transitiontransition defines how the animation changes from one state to another, specifying timing and style changes.trigger('openClose', [
state('open', style({ height: '200px' })),
state('closed', style({ height: '100px' })),
transition('open => closed', [animate('300ms ease-out')]),
transition('closed => open', [animate('300ms ease-in')])
])
What will happen when the component's state changes from 'closed' to 'open'?trigger('toggle', [
state('on', style({ opacity: 1 })),
state('off', style({ opacity: 0 })),
transition('on <=> off', animate('400ms ease-in-out'))
])
Why might this code cause an error or unexpected behavior?animate() to be wrapped in an array [].'on <=> off' is valid for bidirectional transitions, duration '400ms ease-in-out' has units, and transition is correctly placed outside states.