Search code examples
angularangular-animations

How to use angular animation in child component


I have an animation defined in app component

@Component({
  selector: 'app-root',
  styleUrls: ['./app.component.css'],
  templateUrl: './app.component.html',
  encapsulation: ViewEncapsulation.None,
  animations: [
    trigger('fade', [
      state('void', style({
        opacity: 0
      })),
      transition(':enter, :leave', [
        animate(4000)
      ])
    ])
  ]
})
export class AppComponent {
  title = 'app';
}

I want to apply the animation in a child component without redefining it in the child component, how can i achieve this


Solution

  • You have to keep your animations in a shared file. In that way, it will be really helpful for you to manage it.

    You can see this - https://github.com/commutatus/angular-starterpack/tree/master/src/app/shared

    In shared/animations you will find the animation, and you can then import these animations in your components.

    For importing in component -

    import {fadeIn} from '~app/shared/animations/index';
    
    @Component({
      selector: 'app-root',
      styleUrls: ['./app.component.css'],
      templateUrl: './app.component.html',
      encapsulation: ViewEncapsulation.None,
      animations: [
        fadeIn
      ]
    })
    

    Note - Don't forget to import BrowserAnimationModule in your app.module.ts. Also, export the animations from the shared/animation/index