InterviewHubPRO
Section Overview
Q251

Question 251 of 283

Part 9: NgModules, Providers, NgZone & Injector Hierarchies (213 - 255)

89%
Angular & Signals (283 Qs)•Part 9: NgModules, Providers, NgZone & Injector Hierarchies (213 - 255)

How do you trigger an animation?

Angular provides a trigger() function for animation in order to collect the states and transitions with a specific animation name, so that you can attach it to the triggering element in the HTML template. This function watch for changes and trigger initiates the actions when a change occurs. For example, let's create trigger named upDown, and attach it to the button element.

js
content_copy
@Component({
selector: 'app-up-down',
animations: [
  trigger('upDown', [
    state('up', style({
      height: '200px',
      opacity: 1,
      backgroundColor: 'yellow'
    })),
    state('down', style({
      height: '100px',
      opacity: 0.5,
      backgroundColor: 'green'
    })),
    transition('up => down', [
      animate('1s')
    ]),
    transition('down => up', [
      animate('0.5s')
    ]),
  ]),
],
templateUrl: 'up-down.component.html',
styleUrls: ['up-down.component.css']
})
export class UpDownComponent {
isUp = true;

toggle() {
  this.isUp = !this.isUp;
}