Skip to content

Instantly share code, notes, and snippets.

@preyneyv
Created August 2, 2019 03:26
Show Gist options
  • Select an option

  • Save preyneyv/401033e78bce4ce41895997f64ab0651 to your computer and use it in GitHub Desktop.

Select an option

Save preyneyv/401033e78bce4ce41895997f64ab0651 to your computer and use it in GitHub Desktop.

Angular Route Transition

This will be a very simple fade transition between routes for Angular.

First, import the BrowserAnimationsModule into your app.module.ts

Create a file called app/animations.ts.

// Define the animation.
export const routeFadeTransition = trigger('routeAnimations', [
  transition('* <=> *', [
    // Set the container position to relative
    style({ position: 'relative' }),
    
    // Setup the entering and exiting view styles for animation.
    query(':enter, :leave', [
      style({
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%'
      })
    ], { optional: true }),
    
    // Hide the entering view
    query(':enter', [ style({ opacity: 0 }) ], { optional: true }),
    
    // Run child animations for exiting view
    query(':leave', animateChild(), { optional: true }),
    
    // Fade out exiting view
    query(':leave', [
      animate('300ms ease', style({ opacity: 0 }), { optional: true })
    ]),
    
    // Fade in entering view
    query(':enter', [
      animate('300ms ease', style({ opacity: 1 }), { optional: true })
    ]),
    
    // Run child animations for entering view
    query(':enter', animateChild(), { optional: true })
  ])
])

Then, under app.component.html (or wherever your router-outlet is),

<div [@routeAnimations]="prepareRoute(outlet)" class="container">
  <router-outlet #outlet='outlet'></router-outlet>
</div>

After that, in the class file (app.component.ts),

@Component({
  // ...
  animations: [
    routeFadeTransition
  ]
})
export class AppComponent {
  prepareRoute(outlet: RouterOutlet) {
    return outlet && outlet.activatedRouteData && outlet.activatedRouteData.animation;
  }
}

Finally, under your app-routing.module.ts, add a unique data attribute called animation to each route.

const routes: Routes = [
  { path: 'login', component: LoginComponent, data: {animation: 'login'} },
  { path: 'dashboard', component: DashboardComponent, data: {animation: 'dashboard'} }
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment