w3resource

Reusable Animations

The AnimationOptions interface in Angular animations enables you to create animations that you can reuse across different components.

Creating reusable animations

To create a reusable animation, use the animation() method to define 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 app components using the `useAnimation()' API, as shown in the code snippet below.

TypeScript Code:

import {
  animation, trigger, animateChild, group,
  transition, animate, style, query
} from '@angular/animations';

export const transAnimation = animation([
  style({
    height: '{{ height }}',
    opacity: '{{ opacity }}',
    backgroundColor: '{{ backgroundColor }}'
  }),
  animate('{{ time }}')
]);

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen reusable-animation by w3resource (@w3resource) on CodePen.


In the above code snippet, transAnimation is made reusable by declaring it as an export variable.

Note: The height, opacity, backgroundColor, and time inputs are replaced during runtime.

We can import the reusable transAnimation variable in your component class and reuse it using the 'useAnimation()' method as shown below.

TypeScript Code:

import { Component } from '@angular/core';
import { useAnimation, transition, trigger, style, animate } from '@angular/animations';
import { transAnimation } from './animations';

@Component({
    trigger('openClose', [
      transition('open => closed', [
        useAnimation(transAnimation, {
          params: {
            height: 0,
            opacity: 1,
            backgroundColor: 'red',
            time: '1s'
          }
        })
      ])
    ])
  ],
})

Live Demo:

It is just a code snippet explaining a particular concept and may not have any output

See the Pen animation-transition by w3resource (@w3resource) on CodePen.


Previous: Complex Sequences
Next: Security



Follow us on Facebook and Twitter for latest update.