How can I handle the back button action on Ionic 2?
I want to be able to know what to do depending on which page is being shown to the user.
I didn\'t find a
I found the Easiest way, just add the following code in
app.component
:
this.platform.registerBackButtonAction((event) => {
let activePortal = this.ionicApp._loadingPortal.getActive() ||
this.ionicApp._modalPortal.getActive() ||
this.ionicApp._toastPortal.getActive() ||
this.ionicApp._overlayPortal.getActive();
if(activePortal && activePortal.index === 0) {
/* closes modal */
activePortal.dismiss();
} else {
if(this.nav.getActive().name == 'Homepage') { // your homepage
this.platform.exitApp();
}
else {
if(this.nav.canGoBack())
this.nav.pop();
this.nav.setRoot(Homepage);
}
}
},101);
That's it! No need to add extra code on every page!
Here's how I did it:
In every Page component, I created a function called backButtonAction()
, which will execute custom code for every page.
Code:
import { Component } from '@angular/core';
import { Platform, NavController, ModalController } from 'ionic-angular';
import { DetailsModal } from './details';
@Component({
selector: 'page-appointments',
templateUrl: 'appointments.html'
})
export class AppointmentsPage {
modal: any;
constructor(private modalCtrl: ModalController, public navCtrl: NavController, public platform: Platform) {
// initialize your page here
}
backButtonAction(){
/* checks if modal is open */
if(this.modal && this.modal.index === 0) {
/* closes modal */
this.modal.dismiss();
} else {
/* exits the app, since this is the main/first tab */
this.platform.exitApp();
// this.navCtrl.setRoot(AnotherPage); <-- if you wanted to go to another page
}
}
openDetails(appointment){
this.modal = this.modalCtrl.create(DetailsModal, {appointment: appointment});
this.modal.present();
}
}
And in the app.component.ts
, I used the platform.registerBackButtonAction
method to register a callback that will be called everytime the back button is clicked. Inside it I check if the function backButtonAction
exists in the current page and call it, if it doesn't exists, just go to the main/first tab.
One could simplify this if they didn't need to perform customized actions for every page. You could just pop or exit the app.
I did it this way because I needed to check if the modal was open on this particular page.
Code:
platform.registerBackButtonAction(() => {
let nav = app.getActiveNav();
let activeView: ViewController = nav.getActive();
if(activeView != null){
if(nav.canGoBack()) {
nav.pop();
}else if (typeof activeView.instance.backButtonAction === 'function')
activeView.instance.backButtonAction();
else nav.parent.select(0); // goes to the first tab
}
});
if the current page is the first tab, the app closes (as defined in the backButtonAction
method).
Actually ionViewWillLeave
works better in my case.
Here are the official docs about navigating lifecycle
I have Researched Many Things for back button handle Finally I Found a Good Solution for ionic latest Version 3.xx
//Check Hardware Back Button Double Tap to Exit And Close Modal On Hardware Back
let lastTimeBackPress = 0;
let timePeriodToExit = 2000;
this.platform.registerBackButtonAction(() => {
let activePortal = this.ionicApp._loadingPortal.getActive() || // Close If Any Loader Active
this.ionicApp._modalPortal.getActive() || // Close If Any Modal Active
this.ionicApp._overlayPortal.getActive(); // Close If Any Overlay Active
if (activePortal) {
activePortal.dismiss();
}
else if(this.nav.canGoBack()){
this.nav.pop();
}else{
//Double check to exit app
if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) {
this.platform.exitApp(); //Exit from app
} else {
this.toast.create("Press back button again to exit");
lastTimeBackPress = new Date().getTime();
}
}
});
Ionic Latest version 3.xx app.component.ts file
import { Platform, Nav, Config, ToastController} from 'ionic-angular';
constructor(public toastCtrl: ToastController,public platform: Platform) {
platform.ready().then(() => {
//back button handle
//Registration of push in Android and Windows Phone
var lastTimeBackPress=0;
var timePeriodToExit=2000;
platform.registerBackButtonAction(() => {
// get current active page
let view = this.nav.getActive();
if(view.component.name=="TabsPage"){
//Double check to exit app
if(new Date().getTime() - lastTimeBackPress < timePeriodToExit){
this.platform.exitApp(); //Exit from app
}else{
let toast = this.toastCtrl.create({
message: 'Press back again to exit App?',
duration: 3000,
position: 'bottom'
});
toast.present();
lastTimeBackPress=new Date().getTime();
}
}else{
// go to previous page
this.nav.pop({});
}
});
});
}
you can try this functions :
registerBackButton() {
this.platform.registerBackButtonAction(() => {
if (this.menu.isOpen()) {
console.log("Menu is open!", "loggedInMenu");
this.menu.close();
console.log("this.menu.isOpen(): " + JSON.stringify(this.menu.isOpen()));
return;
}
console.log("Checking for other pages");
let checkHomePage = true;
let max = Globals.navCtrls.length;
for (let i = 0; i < Globals.navCtrls.length; i++) {
let n = Globals.navCtrls[i];
if (n) {
if (n.canGoBack()) {
console.log("Breaking the loop i: " + JSON.stringify(i));
let navParams = n.getActive().getNavParams();
if (navParams) {
console.log("navParams exists");
let resolve = navParams.get("resolve");
if (resolve) {
n.pop().then(() => resolve({}));
} else {
n.pop();
}
} else {
n.pop();
}
checkHomePage = false;
return;
}
} else console.log("n was null!");
}
if (this.nav.getActive().instance instanceof TabsPage && !this.nav.canGoBack()) {
let popPageVal = this.backbuttonService.popPage();
console.log("popPageVal: " + JSON.stringify(popPageVal));
if (popPageVal >= 0) {
console.log("Switching the tab to: ", popPageVal);
this.switchTab(popPageVal);
} else {
console.log("Last page is HomePage");
if (this.alert) {
this.alert.dismiss();
this.alert = null;
} else {
this.showAlert();
}
}
} else {
console.log("Last page is not HomePage");
if (this.nav.canGoBack()) {
console.log("We can go back!");
this.nav.pop();
}
}
});
}
showAlert() {
this.alert = this.alertController.create({
title: "Exit?",
message: "Are you sure you want to exit?",
buttons: [
{
text: "Cancel",
role: "cancel",
handler: () => {
this.alert = null;
}
},
{
text: "Exit",
handler: () => {
this.platform.exitApp();
}
}
]
});
this.alert.present();
}
switchTab(tabIndex) {
if (Globals.tabs && tabIndex >= 0) {
console.log("Switch condition met");
Globals.tabIndex = tabIndex;
Globals.tabs.select(tabIndex);
Globals.tabs.selectedIndex = tabIndex;
}
}
I hope its works with you.