[Ionic 4] Confirm on back button press

Hi guys,

Today I’m trying to implement an alert confirm popup when I try to leave one of my pages, either with the software backbutton or the hardware one.

Here’s how I tried to achieve this:

ionViewWillLeave() {
    this.alert.confirmLeavingFiche();
}
async confirmLeavingFiche() {
    return await this.alert.create({
      header: 'Attention !',
      backdropDismiss: false,
      message: 'Voulez-vous vraiment retourner à votre fiche ? Les modifications non-enregistrées seront perdues.',
      buttons: [
        {
          text: 'Non',
          role: 'cancel',
          cssClass: 'secondary',
          handler: reject
        }, {
          text: 'Oui',
          handler: resolve
        }
      ]
    }).then(a => {
      a.present().then();
    });
}

So, this is the code which is on the page I want to leave. But I want the user to be sure he wants to leave it, so when he clicks on the back button, I want to show this alert asking if he’s sure about it and he will lose his informations etc.

But when I click on the back button, it is actually getting back and then it shows the alert that is useless since we left our page already.

Feel free to ask me any question !

I can also upload a short video showing the actual behavior if it’s needed.

Thanks :wink:

2 Likes

Same problem. Need this for various reasons

This found for me.

import { AlertController } from '@ionic/angular';
import {Router} from '@angular/router'

constructor( public alertController: AlertController, private _Router:Router ) { }

async confirmLeavingFiche() {
    const alert = await this.alertController.create({
        header: 'Attention !',
        message: 'Voulez-vous vraiment retourner à votre fiche ? Les modifications non-enregistrées seront perdues.',
        buttons: [
          {
            text: 'Non',
            role: 'cancel',
            cssClass: 'secondary',
            handler: (blah) => {}
          }, {
            text: 'Oui',
            handler: () => {
              this._Router.navigate(['/URL_Back_Route']); //Change **URL_Back_Route** for your Router
            }
          }
        ]
      });
  
      await alert.present();
    }