Search code examples
angulartypescriptangular-routingangular-animations

Angular router animation not triggering


In my angular app I would like the router transitions be animated: the leaving component should fade-out and after that, the entering component should fade in. Basic stuff I would say :)

So I created this stackblitz (some of the code in there was copied from elsewhere), but my main resource was the Angular Route transition animations

But, as you can see, for some reason the animations doesn't do anything.

Here is my animation code

export const routerTransition = trigger("routeAnimations", [
  transition("* => *", [
    query(":enter, :leave", style({ position: "fixed", width: "100%" })),
    query(":enter", style({ transform: "translateX(100%)" })),
    sequence([
      query(":leave", animateChild()),
      query(":leave", [
        style({ opacity: 1 }),
        animate(
          "1000ms cubic-bezier(.75,-0.48,.26,1.52)",
          style({ opacity: 0 })
        )
      ]),
      query(":enter", [
        style({ transform: "translateX(0)", opacity: 0 }),
        animate(
          "1000ms cubic-bezier(.75,-0.48,.26,1.52)",
          style({ opacity: 1 })
        )
      ]),
      query(":enter", animateChild())
    ])
  ])
]);

Also, here is the HTML from app.component, because thats the place where I connect the animation with the router

<main [@routeAnimations]="prepareRoute(outlet)">
    <router-outlet #outlet="outlet"></router-outlet>
</main>

And the prepareRoute looks like:

prepareRoute(outlet: RouterOutlet) {
   return (
     outlet && outlet.activatedRouteData && outlet.activatedRouteData.animation
   );

}

All according to the docs, so I'm a bit lost here with the animations so any help would be appreciated!


Solution

  • You have two issues in your example

    1. You're missing BrowserAnimationsModule in your AppModule. Consider adding it into imports section from "@angular/platform-browser/animations" package
    2. If you check your prepareRoute function, you can see that it utilizes the animation property from the activated route data. The same is in the docs that you refer to. However, your route data is missing. Consider adding at least
      {
         path: "foo",
         component: FooComponent,
         data: { animation: true }
      }
      
      to the foo path, and your animations start working.

    Here you can find a fixed example however I'd advise you to check the docs more precisely because you can define animation names that you do not use for now.