Router animation in angular

In this article we discuss how to set-up animation for between two routes.

For routing animation we need to implemnt implement in compoent using function(trigger, state, animate, transition, style) from the new ‘@angular/animations’ package

First we need to import BrowserAnimationsModule in our module file “app.module.ts”


......
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
......
@NgModule({
    imports: [
        ...
        BrowserAnimationsModule
    ],
    ...
})
export class AppModule { }

Lets create Side In/Out animation for compoent.


// import the required animation functions from the angular animations module
import { trigger, state, animate, transition, style } from '@angular/animations';

export const slideInOutAnimation =
   
    trigger('slideInOutAnimation', [

        // route  start Style
       // we ste background for the component load.
        state('*', style({
            // the view covers the whole screen with a semi tranparent background
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'rgba(0, 0, 0, 0.4)'
        })),

        // route 'enter' transition
        transition(':enter', [

            // start of transition
            style({
                right: '-400%',
                backgroundColor: 'rgba(0, 0, 0, 0)'
            }),

            // animation transition
            animate('.5s ease-in-out', style({
                right: 0,
                backgroundColor: 'rgba(0, 0, 0, 0.8)'
            }))
        ]),

        // route 'leave' transition
        transition(':leave', [
           
            animate('.5s ease-in-out', style({
                right: '-400%',
                backgroundColor: 'rgba(0, 0, 0, 0)'
            }))
        ])
    ]);

We need to import these animation in our component where we need to use For that we need to import in our compoent.


............
// import slidein/out in animation
import { slideInOutAnimation } from '../animations/index';
-----------
@Component({
  
    templateUrl: 'slideinout.html',

    // make slide in/out animation available to this component
    animations: [slideInOutAnimation],

    // attach the slide in/out animation to the (root) element of this component
    host: { '[@slideInOutAnimation]': '' }
})

Below is the full example how to create Slide In/Out.