Animations are determined in the metadata of the component that controls the HTML element to be animated. Put the code that defines your animations under the animations: property within the @component () decorator.
Open-and-close.component.ts
import { animate, state, style, transition, trigger } from '@angular/animations';
import { Component } from '@angular/core';
@Component({
selector: 'app-open-and-close',
animations: [
trigger('openClose', [
// ...
state('open', style({
height: '250px',
opacity: 1,
backgroundColor: 'orange'
})),
state('closed', style({
height: '200px',
opacity: 0.5,
backgroundColor: 'blue'
})),
transition('open => closed', [
animate('1s')
]),
transition('closed => open', [
animate('0.5s')
]),
]),
],
templateUrl: './open-and-close.component.html',
styleUrls: ['./open-and-close.component.css']
})
export class OpenAndCloseComponent {
isOpen = true;
toggle() {
this.isOpen = !this.isOpen;
}
}
When you have determined an animation trigger for a component you can attach it to an element in that component's template by wrapping the trigger name in brackets and preceding it with an @symbol. Then you can bind the trigger to a template expression through standard Angular property binding syntax as the following, where triggerName is the name of trigger and expression assesses to a defined animation state.
...
The animation is executed or triggered once the expression value modifies to a new state.
The animation is executed or triggered once the expression value modifies to a new state.
The following code binds the trigger to the value of the isOpen property.
Open-and-close.component.html
Now the box is {{isOpen?'Open':'Closed'}}!
Open-and-close.component.css
:host {
display: block;
}
.open-and-close-container {
border: 2px solid #dddddd;
margin-top: 2em;
padding: 30px 30px 0px 30px;
color: green;
font-weight: bold;
font-size: 22px;
}
Output

Figure 3: Output of the above example code snippet
In the above 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 is up to the openClose code to handle the state change and start a state change animation.
For elements opening or leaving a page, you can make the animations conditional, For example, use *ngIf with the animation trigger in the HTML template.