...

/

States and Transitions

States and Transitions

Learn how to use Angular animations to animate the transitions between different element states.

Angular lets us define a style to be applied to an element for each state and a transition to animate the element’s styling changes. States in Angular animations are defined through the state() function or by using the predefined states Angular offers.

Custom states

Angular allows us to use any string to name a state. These strings can then be used in the transition function to define the animation as the element’s state changes.

Take the code snippet below as an example. There are two states—- default(line 19) and disabled (line 25) with their respective styles. The state names are then passed into the transition function to specify the animation. The default => disabled function (line 31) describes the transition to be applied when the element’s state changes from default to disabled. On the other hand, disabled => default (line 32) describes the transition to be applied when the element’s state changes from disabled to default.

Press + to interact
// app.component.ts
import { Component } from "@angular/core";
import {
animate,
state,
style,
transition,
trigger,
} from "@angular/animations";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"],
// Animations code 👇
animations: [
trigger("buttonAnimations", [
state(
"default",
style({
opacity: 1,
})
),
state(
"disabled",
style({
opacity: 0.5,
})
),
transition("default => disabled", [animate("1s")]),
transition("disabled => default", [animate("0.5s")]),
]),
]
})
export class AppComponent {}

To help you understand, let’s look at a visual depiction of the animation from the code above.

Press + to interact
Visualization of Angular animations with custom states
Visualization of Angular animations with custom states

Example

Let’s walk through the implementation in a complete Angular application.

  1. Before creating the animation, first create the button element in our template and attach a click event listener to it that will call a function. The function will then
...