Search code examples
angularanimationcomponentsangular-animations

One reusable animation for multiple Angular components?


I am using animations in my Angular app, and many components use the same animation but for that I copy/paste the animation in each component. Can we reuse the animations without applying it on individual components.


Solution

  • You should create an animations.ts file, and import the animation you want in each component:

    Example animations.ts

    import {
      trigger,
      style,
      animate,
      transition,
      state,
      group
    } from '@angular/animations';
    
    
    export const rotations = [
      trigger('rotatedState', [
        state('default', style({
          transform: 'rotate(0)'
        })),
        state('rotated', style({
          transform: 'rotate(-180deg)'
        })),
        transition('rotated => default',
          animate('400ms ease-out')
        ),
        transition('default => rotated',
          animate('400ms ease-in')
        )
      ])
    ];
    
    export const someOtherAnimations = [
      ...
    ];
    

    Now import in component.ts:

    import { rotations } from 'app/animations';
    
    @Component({
      ...
      animations: [rotations],
    })
    

    Now you can use in your component.html:

    <img @rotatedState >