Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 me to close an opened modal. How can I detect if I'm in a modal to close it ?

platform.registerBackButtonAction(() => {

      let nav = app.getActiveNav();
      let activeView: ViewController = nav.getActive();
      console.log(activeView);

      if(activeView != null){
        if(nav.canGoBack()) {
          activeView.dismiss();
        } else{
          let alert = this.alertCtrl.create({
            title: this.pdataManager.translate.get("close-app"),
            message: this.pdataManager.translate.get("sure-want-leave"),
            buttons: [
              {
                text: this.pdataManager.translate.get("no"),
                handler: () => {
                  this.presentedAlert = false;
                },
                role: 'cancel',
              },
              {
                text: this.pdataManager.translate.get("yes"),
                handler: () => {
                  this.presentedAlert = false;
                  this.platform.exitApp();
                }
              }
            ]
          });
          if(!this.presentedAlert) {
            alert.present();
            this.presentedAlert = true;
          }
        }
      }
    });
  }
like image 897
V. Pivet Avatar asked Oct 10 '17 08:10

V. Pivet


2 Answers

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

like image 196
Alexis_Ni Avatar answered Nov 13 '22 15:11

Alexis_Ni


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';
like image 3
DwlRathod Avatar answered Nov 13 '22 16:11

DwlRathod