Handling hardware Backbutton after a Button inside a Menu opens a Modal


I have an app with a Sidemenu.

On this menu there’s a div tappable that opens a Modal which serves me as a pseudo-select box

    let modal = this.modalCtrl.create('SelectPage');

    modal.onDidDismiss(option => {


The problem is: If the user tap the Backbutton It doesn’t (instantly) close the Modal. First it closes the Sidemenu (behind the modal) then If I tap again it closes de Modal.

I thought it should close the Modal first… Any help?


You could override the functionality of the Android back button. This can be done using this.platform.registerBackButtonAction but when you do so you need to add all the functionality of it yourself. This includes the closing of overlay portals (modals, toasts, alerts), popping pages off the nav stack, closing the side menu, closing the app, and going to previous tabs. I have included all of these except for previous tabs. If you want to attempt to do that see https://hackernoon.com/handling-android-back-button-in-ionic-33f7cfbba4b9

Another resource for getting the modals to close was https://github.com/ionic-team/ionic/issues/6982

// app.component.ts
exitToast: Toast;
lastTimeBackPress = 0;
timePeriodToExit = 2000;

constructor(public platform: Platform,
          public toastCtrl: ToastController,
          private ionicApp: IonicApp,
          private menu: MenuController) {

initializeApp() {
   this.platform.ready().then(() => {
      this.platform.registerBackButtonAction(() => {
         if (this.exitToast !== undefined) {
            this.exitToast.dismiss().then(() => {
         } else {

closeOpenItem() {
   let activePortal = this.ionicApp._loadingPortal.getActive() ||
    this.ionicApp._modalPortal.getActive() ||
    this.ionicApp._toastPortal.getActive() ||
   if (activePortal) {
     activePortal.onDidDismiss(() => {
   } else if (this.menu.isOpen()) {
   } else if (this.nav.canGoBack()) {
   } else {
      if (new Date().getTime() - this.lastTimeBackPress < 
          this.timePeriodToExit) {
      } else {
         this.exitToast = this.toastCtrl.create({
            message: 'Press back button again to exit',
            duration: 1000,
            position: 'top'
         this.lastTimeBackPress = new Date().getTime();

Answered By – Garrett Barlocker

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published