Ionic 3 : Close Modal With Phone's Back Button
I try to override the phone's back button in my Ionic App. This code permit me to open a modal to close the App if I'm not in a page, else close the page. But this doesn't allow
Solution 1:
1.Import IonicApp:
import {IonicApp } from'ionic-angular';
2.Add to your constructor:
private ionicApp: IonicApp
3.Inside your platform.registerBackButtonAction add:
let activeModal=this.ionicApp._modalPortal.getActive();
if(activeModal){
activePortal.dismiss();
return;
}
I found the answer here : https://github.com/ionic-team/ionic/issues/6982
Solution 2:
You can give page name to your modal and you can access it from anywhere in app. Try this..
import { App } from'ionic-angular';
constructor(public app: App){
}
platform.registerBackButtonAction(() => {
let nav = this.app.getActiveNav();
let view = nav.getActive().instance.pageName;
if (view == YOU_PAGE_NAME) {
//You are in modal
} else {
//You are not in modal
}
});
Inside your modal
pageName = 'YOU_PAGE_NAME';
Solution 3:
In the end I have this for my back button:
constructor(private platform: Platform, private config: ConfigService, private nfc: NfcService, private alertCtrl: AlertController,
public events: Events, private translate: TranslateService, private fetch: ConfigFetchService, private menuList: MenuList, private ionicApp: IonicApp,
private menuCtrl: MenuController
) {
platform.ready().then(() => {
this.config.pullVersion();
let ready = true;
platform.registerBackButtonAction(() => {
Logger.log("Back button action called");
let activePortal = ionicApp._loadingPortal.getActive() ||
ionicApp._modalPortal.getActive() ||
ionicApp._toastPortal.getActive() ||
ionicApp._overlayPortal.getActive();
if (activePortal) {
ready = false;
activePortal.dismiss();
activePortal.onDidDismiss(() => { ready = true; });
Logger.log("handled with portal");
return;
}
if (menuCtrl.isOpen()) {
menuCtrl.close();
Logger.log("closing menu");
return;
}
let view = this.nav.getActive();
let page = view ? this.nav.getActive().instance : null;
if (page && page.isRootPage) {
Logger.log("Handling back button on a home page");
this.alertCtrl.create({
title: translate.instant('Confirmation'),
message: translate.instant('Do you want to exit?'),
buttons: [
{
text: translate.instant('Cancel'),
handler: () => {
}
},
{
text: translate.instant('OK'),
handler: () => {
platform.exitApp();
}
}
]
}).present();
}
elseif (this.nav.canGoBack() || view && view.isOverlay
) {
Logger.log("popping back");
this.nav.pop();
}
elseif (localStorage.getItem('is_logged_in')
) {
Logger.log("Returning to home page");
this.nav.setRoot(HomePage);
}
elseif (!localStorage.getItem('is_logged_in')) {
Logger.log("Not yet logged in... exiting");
platform.exitApp();
}
else {
Logger.log("ERROR with back button handling");
}
}, 1);
....
Post a Comment for "Ionic 3 : Close Modal With Phone's Back Button"