Blog>
Snippets

Route Transition Animations with Angular Router

Implement advanced route transition animations between components with the Angular Router, using grouped animation timelines to manage complex animations.
import { trigger, transition, group, query, style, animate } from '@angular/animations';

export const slideInAnimation =
  trigger('routeAnimations', [
    transition('HomePage <=> AboutPage', [
      style({ position: 'relative' }),
      query(':enter, :leave', [
        style({
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%'
        })
      ]),
      query(':enter', [
        style({ left: '-100%' })
      ]),
      group([
        query(':leave', [
          animate('600ms ease-out', style({ left: '100%' }))
        ]),
        query(':enter', [
          animate('600ms ease-out', style({ left: '0%' }))
        ])
      ])
    ])
  ]);
Defines the slideInAnimation for the Angular Router animations. This setup assumes two routes named 'HomePage' and 'AboutPage'. It animates the transition between these two components. Both pages slide in and out in sync during the navigation.
import { Component } from '@angular/core';
import { slideInAnimation } from './animations';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [slideInAnimation]
})
export class AppComponent {
  prepareRoute(outlet) {
    return outlet && outlet.activatedRouteData && outlet.activatedRouteData['animation'];
  }
}
Integrates the slideInAnimation into the AppComponent and provides a method to determine if the route should be animated based on the 'animation' data property provided in the route's configuration.
<router-outlet #outlet="outlet" [@routeAnimations]="prepareRoute(outlet)"></router-outlet>
Updates the router-outlet element in your app.component.html to use the slideInAnimation and activates it based on the prepareRoute method.
const routes: Routes = [
  { path: '', redirectTo: '/homepage', pathMatch: 'full' },
  { path: 'homepage', component: HomepageComponent, data: { animation: 'HomePage' } },
  { path: 'about', component: AboutComponent, data: { animation: 'AboutPage' } }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Configures the routing module by setting up routes. Each route has a data property that includes an animation key corresponding to the names used in the slideInAnimation transitions.