Routing Animation in Angular

Add style to your application by animating your route transitions!

Shilpa Lalwani
Angular In Depth
6 min readApr 6, 2020

--

Icon Courtesy: animation by Flatart from the Noun Project

Well, you might think, Why Animations?🤔

I’d say why not? Animations are awesome ❤️❤️

Animation are used to make transitions more obvious, so it’s clear what happened between where the user started and ended up. Consider this , Web app navigates through the sections of the page with link, which means Clicking a link jumps to a new position on the same page.

If there’s no transition, it isn’t clear that the page was automatically scrolled down and this is confusing. Animation shows how the user caused the action. Compare the following two images:

Navigation without Animation
Navigation with Animation

Animations can improve your app and user experience in a number of ways:

  • Without animations, web page transitions can seem abrupt and jarring.
  • Enhances the user experience, so animations give users a chance to detect the application’s response to their actions.
  • Good animations intuitively call the user’s attention to where it is needed.

Now how do we implement animations? 🤷🏻‍♀️

Animations in Angular are implemented inside components using a set of functions (trigger, state, animate, transition, style) from the @angular/animations package. Animation styles are defined using CSS rules, but they are defined in TypeScript using JSON objects instead of CSS/LESS files, there is also an Angular Animation DSL (Domain Specific Language) for controlling different states and transitions between states.

There are following core functions that are used in defining animation in angular

> State

State creates a named set of CSS styles that should be applied on successful transition to a given state. There are 2 types of states:

  • Defaults:
    - void : when the element is not present in the view, it is in the void state.
    - * : wildcard, match any state.
  • Custom:
    States defined by using state().

> Transition

Transition defines the animation sequence between two named states.

> Trigger

This is the animation name we will use when binding the animation to an expression which will trigger it.

> Animate

Specifies the timing information for a transition.

Route Animation in Angular

Adding animations can create an excellent user experience when applied appropriately in an application.

Angular provides a beautiful way to animate the transition between the routes using Route Transition Animation.To produce an animation sequence when switching between routes, we need to define nested animation sequences.

✔️Prerequisites:

  1. Basics of Angular routing and components
  2. Basics of animation properties.

Let’s Start Coding 🙇

I won’t bore you with building an entire application. We’ll get right to adding animations so you can see immediate results.

I have already created Article application with basic routing for following 2 routes

  • home
  • article

The base code for this example can be found here. Now let’s start with routing animations 🤟

Step 1: Adding Router Animation Module to App Module

In order to add animation in the application we will add BrowserAnimationsModule module from @angular/platform-browser/animations in our main app.module.ts file. eg.

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

And also add it to our @NgModule decorator’s import array.

Step 2: Creating Route Animation

A few important notes before starting with animations:

  • The trigger name must match the trigger used in the app component HTML.
  • When an animation is triggered we have access to the previous page via the :leave selector, and the current page via the :enter selector. We can query these elements to style and animate them.
  • Using wildcard syntax like * <=> * applies the default animation to all routes.

Angular uses arrow syntax to define the transition from one state to another. For example, if we want to handle the navigation from One to Two we use One => Two. If we want to handle both directions, we can use a bi-directional arrow, One <=> Two, and then the transition will be applied going from One to Two and from Two to One.

Angular has some powerful pre-defined concepts in addition to the named states.

  • void = an element is entering or leaving the view.
  • * = any state
  • :enter and :leave are aliases for the void => * and * => void transitions.

Let’s create file for animation route-animation.ts

import {
transition,
trigger,
query,
style,
animate,
group,
animateChild
} from '@angular/animations';
export const slideInAnimation =
trigger('routeAnimations', [
transition('Home => *', [
query(':enter, :leave',
style({ position: 'fixed', width: '100%' }),
{ optional: true }),
group([
query(':enter', [
style({ transform: 'translateX(100%)' }),
animate('0.5s ease-in-out',
style({ transform: 'translateX(0%)' }))
], { optional: true }),
query(':leave', [
style({ transform: 'translateX(0%)' }),
animate('0.5s ease-in-out',
style({ transform: 'translateX(-100%)' }))
], { optional: true }),
])
]),
transition('Article => Home', [
query(':enter, :leave',
style({ position: 'fixed', width: '100%' }),
{ optional: true }),
group([
query(':enter', [
style({ transform: 'translateX(-100%)' }),
animate('0.5s ease-in-out',
style({ transform: 'translateX(0%)' }))
], { optional: true }),
query(':leave', [
style({ transform: 'translateX(0%)' }),
animate('0.5s ease-in-out',
style({ transform: 'translateX(100%)' })
], { optional: true }),
])
]),
]);

Step 3 : Adding animation to our routing

In app-routing.module.ts we need to pass data to identify the current route while doing the route transition animation, to achieve this we will add data object with animation property . Make sure to do the following changes in your routing file.

const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: '/home' },
{ path: 'home', component: HomeComponent , data: {animation: 'Home'} },
{ path: 'article/:id', component: ArticleComponent , data: {animation: 'Article'} },
];

We can also pass data into the router to customize animations on a component-by-component basis. For example, we might need the animation for the specific component which is present somewhere in the UI.

Step 4: Wrapping Router Outlet

Most important parts of the section where we will wrap it with the animation directive @routeAnimations. In this, we define the method which gets assigns an animation state value to the animation trigger (@routeAnimation) based on the route configuration data property value.

In app.component.html, wrap <router-outlet> with <div> and create reference variable of outlet as o.

<div [@routeAnimations]="o && o.activatedRouteData 
&& o.activatedRouteData['animation']">
<router-outlet #o="outlet"></router-outlet>
</div>

Last but not the least add slideInAnimation we created in the last step in app.component.ts animations array

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
animations: [ slideInAnimation ]
})

That’s it. Our Angular application with beautiful route transition animation is done. See the final app below.

Well done

Voila! Successful Angular route transition animations!

This just scratches the surface of what can be done with Angular animations.We can also create a library of reusable and complex animations in Angular.

At last Thanks to Siddharth Ajmera for proofreading it and providing feedback in making this article better.

--

--