You are currently viewing Ionic & Angular: Custom page transitions (animations between pages)

Ionic & Angular: Custom page transitions (animations between pages)

Default page transitions that you can find in out of the box Ionic framework does not always suits your needs. In some cases you may want to have custom page animations when ion-router-outlet navigates between pages. Let me share with you a very compact and elegant solution for the title topic.

Watch the tutorial on YouTube

Here you can find the video version of the tutorial.

How to implement a custom page transition in Ionic with Angular

Lets suppose that you want to add fade out effect to all page transitions in your Ionic application. The best place to customize animation for this purpose is ion-router-outlet. According to the Ionic documentation you can pass a custom function as the “animation” property of ion-router-outlet.

Edit app.component.html file and set “myCustomPageTransition” value as the animation property of ion-router-outlet.

<ion-app>
  <ion-router-outlet [animation]="myCustomPageTransition"></ion-router-outlet>
</ion-app>

Then edit app.component.ts file and create myCustomPageTransition property as is shown below. Please not that you can use both enteringEl and leavingEl in your animation.

import { Component } from '@angular/core';

import { AnimationController, Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
myCustomPageTransition = ((baseEl: any, opts?: any) => { 
    console.log("opts.enteringEl:"  + opts.enteringEl); //Entering Element - New Page
    console.log("opts.leavingEl:"  + opts.leavingEl);   //Leaving Element - Current Page
    var anim1 = this.animationCtrl.create()
      .addElement(opts.leavingEl)
      .duration(2000)
      .iterations(1)
      .easing('ease-out')
      .fromTo('opacity', '1', '0.0')
    var anim2 = this.animationCtrl.create()
      .addElement(opts.enteringEl)
      .duration(2000)
      .iterations(1)
      .easing('ease-out')
      .fromTo('opacity', '0.0', '1')
     var anim2 = this.animationCtrl.create()
      .duration(2000)
      .iterations(1)
      .addAnimation([anim1, anim2]);
    return anim2;
});

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private animationCtrl: AnimationController
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }
}

That’s all what I’ve prepared for you in this tutorial, if I helped you, please consider sharing this post to help me gain a wider audience.
Thanks and I hope to see you in my next tutorial.