Back to results for “Animations”
Angular › Angular Animations

How do you define a simple fade in animation using the trigger and transition functions in Angular?

Intermediate

Answer

You define an animation trigger with a name, describe the styles for each state using the state function, and describe how to move between those states using the transition function, then attach the trigger to an element in your template using square brackets and the at symbol.
import { trigger, state, style, transition, animate } from '@angular/animations';

@Component({
  selector: 'app-box',
  template: `<div [@fadeIn]="visible ? 'shown' : 'hidden'">Hello there</div>`,
  animations: [
    trigger('fadeIn', [
      state('hidden', style({ opacity: 0 })),
      state('shown', style({ opacity: 1 })),
      transition('hidden => shown', animate('300ms ease-in'))
    ])
  ]
})
export class BoxComponent { visible = false; }
Real-world example A notification banner fades in smoothly over three hundred milliseconds whenever a new alert appears, making the page feel more polished instead of the banner just suddenly appearing.

Common follow-ups: How would you also animate the banner fading out when it is dismissed?;What is the difference between the state function and simply toggling a CSS class?