Confirm Exit with device back button in ionic


#1

In my app i have 2 pages home.ts and page2.ts, home page has a button to open the page2,

openPage(){
  this.navctrl.push('page2');
}

and in page 2 i have another button that will open a model that is page3 like below

presentModal() {
    let modal = this.modalCtrl.create(page3 );
    modal.present();
}

so far ok, if i opened the modal, pressing device back button will close the modal,and pressing again will pop the page2 and home page wil be now the active page, it will quit the app if i press the device backbutton again.

i want to use a confirm alert box in home page before quit the app, but device backbutton should work normally in other pages (page2, page3) ,

can someone please help me how to do this,?


#2

use lifecycle event ionViewWillLeave() or ionViewWillUnload()


#3

ionViewWillLeave in home.ts will fire when i open the page2


#4

yeah so use WillUnload()


#5

you mean WillUnload fires only when user quit the app ?


#6

ionViewWillUnload Runs when the page is about to be destroyed and have its elements removed.


#7

It is not working

ionViewWillLeave() {
    alert('leave');
}

  ionViewWillUnload() {
    alert('bye');
   // this.appodeal.show(this.appodeal.AD_TYPES.INTERSTITIAL);
  }

it shows alert leave when i open page2, but when i press back button nothing happens, it quits the app,


#8

it is never get called


#9

Here’s what I use: How to hold back twice to exit
Just strip it of things you don’t want :slight_smile:


#10

what i am looking is to show a ad just before the app quit, without much headache with registerbackbutton,and it is very easy with ionic1. i dont understand your code how it works for my need


#11

i hope this helps:


#12

Hi,here i have given my sample coding,refer this coding and where you want use this coding,please use it.

app.component_ file_**
//Import of AlertController in top.
import { AlertController } from ‘ionic-angular’;

@Component({
templateUrl: ‘app.html’
})
export class MyApp {
//Alert shown variavle.
public alertShown:boolean=false;
//parameters passed for platform and AlertController.
constructor(public platform: Platform, public alertCtrl: AlertController) {
platform.registerBackButtonAction(() => {
if (this.alertShown==false) {
this.presentConfirm();
}
}, 0)
}
presentConfirm() {
let alert = this.alertCtrl.create({
title: ‘Confirm you want to Exit’,
message: ‘Do you want Exit?’,
buttons: [
{
text: ‘Cancel’,
role: ‘cancel’,
handler: () => {
console.log(‘Cancel clicked’);
this.alertShown=false;
}
},
{
text: ‘Yes’,
handler: () => {
console.log(‘Yes clicked’);
this.platform.exitApp();
}
}
]
});
alert.present().then(()=>{
this.alertShown=true;
});
}
}

That is it,simply one function in Exit alert controller in ionic v3,Maybe its work correctly,try it


#13

This might Help. Registerbackbuttonaction