Show a confirmation alert before app close ionic

Hello,

I make one application with ionic 2. I am trying to get a confirmation alert before close the application.

How can I do it ?

Greetings.

1 Like

Hello @rpayanm

I need to do the same, could you achieve this?

Yeah :smiley:

showedAlert: boolean;

constructor(..., public alertCtrl: AlertController) {
}

initializeApp() {
    this.platform.ready().then(() => {
        // Okay, so the platform is ready and our plugins are available.
        // Here you can do any higher level native things you might need.
        StatusBar.styleDefault();
        Splashscreen.hide();
        this.showedAlert = false;

        // Confirm exit
        this.platform.registerBackButtonAction(() => {
            if (this.nav.length() == 1) {
                if (!this.showedAlert) {
                    this.confirmExitApp();
                } else {
                    this.showedAlert = false;
                    this.confirmAlert.dismiss();
                }
            }

            this.nav.pop();
        });

    });
}

confirmExitApp() {
    this.showedAlert = true;
    this.confirmAlert = this.alertCtrl.create({
        title: "Salir",
        message: "¿ Esta seguro que desea salir de la aplicación ?",
        buttons: [
            {
                text: 'Cancelar',
                handler: () => {
                    this.showedAlert = false;
                    return;
                }
            },
            {
                text: 'Aceptar',
                handler: () => {
                    this.platform.exitApp();
                }
            }
        ]
    });
    this.confirmAlert.present();
}
1 Like

Thank’s a lot, it works!! :grinning:

@rpayanm answer works well.
BUT breaks navigation in modals.
this.nav.pop(); will pop the view but not close the modal before it.

Where Should i put this code ??

1 Like

in app.components.ts

initializeApp method not executing automatically.
should i call it in constructor or anywhere like ionViewDidLoad ??

Yes, you need to call initialize method from the constructor.
this.initialize()

confirmExitApp() {
this.showedAlert = true;
this.confirmAlert = this.alertCtrl.create({
title: “Salir”,
message: “¿ Esta seguro que desea salir de la aplicación ?”,
buttons: [
{
text: ‘Cancelar’,
handler: () => {
this.showedAlert = false;
return;
}
},
{
text: ‘Aceptar’,
handler: () => {
this.platform.exitApp();
}
}
]
});
this.confirmAlert.present();
}

I have a Error confirmAlert

[ts] Property ‘confirmAlert’ does not exist on type ‘MyApp’.
how to clear this error.

Hi @rpayanm,

I am getting errors due to nav controller when using this code in app.component.ts, how should I use this.nav for this purpose or what should be initialized to this.nav to make it work?