Close Modal in Ionic 4 by Back Button

后端 未结 6 2000
名媛妹妹
名媛妹妹 2021-02-03 12:38

I have a Modal in Ionic 4. I\'d like to close it, when a user press the back button on her mobile (or the bac

6条回答
  •  离开以前
    2021-02-03 12:59

    Based on the initial answer by Markus, You can decide to; Instead of unsubscribing after each back button event. You may want to listen to back-button events globally in your application and only call exit on specific pages.

    import { fromEvent } from "rxjs";           // import fromEvent from rxjs
    import { Router } from "@angular/router";   // import angular router as well
    import { Location } from "@angular/common"; // import location from angular common
        
    constructor(private router: Router, private location: Location) {
    

    // Call the function when the app initializes at app.component.ts. it will watch for // back button events globally in the application.

      this.backButtonEvent();
    }
    
    // Function to present the exit alert
       async exitAlert() {
        const alert = await this.alertController.create({
          // header: 'Confirm!',
          message: "Are you sure you want to exit the app?",
          buttons: [
            {
              text: "Cancel",
              role: "cancel",
              cssClass: "secondary",
              handler: blah => {}
            },
            {
              text: "Close App",
              handler: () => {
                navigator["app"].exitApp();
              }
            }
          ]
        });
    
        await alert.present();
      }
        
          // function to subscribe to the backbutton event
          backButtonEvent(): void {
            const event = fromEvent(document, "backbutton");
            event.subscribe(async () => {
            // When the current route matches a specific page/route in the app where u 
            // want to exit on back button press.
        
            // else assume the user wants to navigate to a previous page
             if(this.router.url === "") { this.exitAlert() 
            }
             else { this.location.back() } 
            });
          } 
    

提交回复
热议问题