'Ionic 4 leaveAnimation on modal.dismiss()

I'm using Ionic 4 with custom modal enter/leave animations. When defining them on modalCtrl.create() the animations work just fine.

Depending on where I am in my app I want to use different modal close animations. For example, Intro page -> Login -> Forgot password. Depending on which one of these pages I'm navigating from/to I want to use different leave/enter animations.

I thought that it would be possible to do the following for a custom leave animation but it seems that leaveAnimation only works when creating the modal, not when dismissing.

Is there any way to define custom animations only on modalCtrl.dismiss()?

this.modalCtrl.dismiss({
  leaveAnimation: this.animations.modalLeave
});


Solution 1:[1]

Imports

import { Animation, AnimationController, ModalController } from '@ionic/angular';

Modal Creation & Options & Animations

async showModal() {

    const leaveAnimation = (baseEl: HTMLElement, opts?: any): Animation => {
        const animationCtrl = new AnimationController();
        const fadeOut = animationCtrl.create()
            .addElement(baseEl)
            .duration(375)
            .keyframes([
               { offset: 0, opacity: '1' }, 
               { offset: 1, opacity: '0' }
             ])
            .iterations(1);

        return animationCtrl.create().addAnimation([fadeOut]);
    }

    const modal = await this.modalCtrl.create({
        ...
        leaveAnimation: leaveAnimation
    });

    await modal.present();
}

Specifications

Ionic CLI                     : 6.17.1 
Ionic Framework               : @ionic/angular 6.0.9
@angular-devkit/build-angular : 13.2.5
@angular-devkit/schematics    : 13.2.5
@angular/cli                  : 13.2.5
@ionic/angular-toolkit        : 6.0.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Grinnex.