angular/aio/content/guide/animations-attach-to-html-template.md

2 KiB

Define animations and attach to an HTML template

Animations are defined in the metadata of the component that controls the HTML element to be animated.

Define the animation

Put the code that defines your animations under the animations: property within the @Component() decorator.

When an animation trigger for a component is defined, attach it to an element in the template. Wrap the trigger name in brackets and precede it with an @ symbol. Bind the trigger to a template expression using standard Angular property binding syntax. The triggerName is the name of the trigger, and expression evaluates to a defined animation state.

<div [@triggerName]="expression">…</div>;

The animation is executed or triggered when the expression value changes to a new state.

The following code snippet binds the trigger to the value of the isOpen property.

In this example, when the isOpen expression evaluates to a defined state of open or closed, it notifies the trigger openClose of a state change. Then it's up to the openClose code to handle the state change and kick off a state change animation.

For elements entering or leaving a page inserted or removed from the DOM, you can make the animations conditional. For example, use *ngIf with the animation trigger in the HTML template.

NOTE:
In the component file, set the trigger that defines the animations as the value of the animations: property in the @Component() decorator.

Attach an animation to an HTML template

In the HTML template file, use the trigger name to attach the defined animations to the HTML element to be animated.

@reviewed 2022-10-28