This topic provides some examples of how to create reusable animations.
Before continuing with this topic, you should be familiar with the following:
To create a reusable animation, use the animation()
function to define an animation in a separate .ts
file and declare this animation definition as a const
export variable. You can then import and reuse this animation in any of your application components using the useAnimation()
function.
import { animation, style, animate, trigger, transition, useAnimation } from '@angular/animations'; export const transitionAnimation = animation([ style({ height: '{{ height }}', opacity: '{{ opacity }}', backgroundColor: '{{ backgroundColor }}' }), animate('{{ time }}') ]);
In the preceding code snippet, transitionAnimation
is made reusable by declaring it as an export variable.
NOTE: The
height
,opacity
,backgroundColor
, andtime
inputs are replaced during runtime.
You can also export a part of an animation. For example, the following snippet exports the animation trigger
.
import { animation, style, animate, trigger, transition, useAnimation } from '@angular/animations'; export const triggerAnimation = trigger('openClose', [ transition('open => closed', [ useAnimation(transitionAnimation, { params: { height: 0, opacity: 1, backgroundColor: 'red', time: '1s' } }) ]) ]);
From this point, you can import reusable animation variables in your component class. For example, the following code snippet imports the transitionAnimation
variable and uses it via the useAnimation()
function.
import { Component } from '@angular/core'; import { transition, trigger, useAnimation } from '@angular/animations'; import { transitionAnimation } from './animations'; @Component({ selector: 'app-open-close-reusable', animations: [ trigger('openClose', [ transition('open => closed', [ useAnimation(transitionAnimation, { params: { height: 0, opacity: 1, backgroundColor: 'red', time: '1s' } }) ]) ]) ], templateUrl: 'open-close.component.html', styleUrls: ['open-close.component.css'] })
You might also be interested in the following:
© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/guide/reusable-animations