How do you create reusable Animations in Angular 2

Rick Strahl picture Rick Strahl · Sep 13, 2016 · Viewed 18.5k times · Source

I'm playing with the Animation API, and I'd like to create a reusable animation like say sliding in content for top level router views. I managed to get through the funky meta data syntax (which is actually pretty cool once get past the crazy idea of using metadata) to get the animations mostly working.

   @Component({
      //moduleId: module.id,
      selector: 'album-display',
      templateUrl: './albumDisplay.html',
      animations: [
        trigger('slideIn', [
          state('*', style({
            transform: 'translateX(100%)',
          })),
          state('in', style({
            transform: 'translateX(0)',
          })),
          state('out',   style({
            transform: 'translateX(-100%)',
          })),
          transition('* => in', animate('600ms ease-in')),
          transition('in => out', animate('600ms ease-in'))
        ])
      ]
  })
  export class AlbumDisplay implements OnInit {
      slideInState = 'in';
      ...
  }

And then assigning that to my top level element in the component:

  <div  class="container" [@slideIn]="slideInState">

So this works, but how can I make this reusable? I don't want to stick this meta data onto every view. Since this is metadata I'm not sure how you could make this reusable.

Answer

ranakrunal9 picture ranakrunal9 · Sep 13, 2016

One possible way is to put animation trigger code in separate file and export it as const variable and use it in component as below.

animations.ts

import { trigger, state, style, transition, animate } from '@angular/core';

export const slideIn = trigger('slideIn', [
  state('*', style({
    transform: 'translateX(100%)',
  })),
  state('in', style({
    transform: 'translateX(0)',
  })),
  state('out',   style({
    transform: 'translateX(-100%)',
  })),
  transition('* => in', animate('600ms ease-in')),
  transition('in => out', animate('600ms ease-in'))
]);

album-display.component.ts

import { slideIn } from './animations'; // path to your animations.ts file

@Component({
    //moduleId: module.id,
    selector: 'album-display',
    templateUrl: './albumDisplay.html',
    animations: [
      slideIn
    ]
})
export class AlbumDisplay implements OnInit {
    slideInState = 'in';
    ...
}