Search code examples
javascriptangular6ionic4

Prevent going back when hardware back button is pressed in Ionic 4 App


    this.platform.backButton.subscribe(()=> {
         const alert = await this.alertController.create({
         header: 'Confirm!',
         message: 'Do you want to go back!!!',
         buttons: [
         {
            text: 'Yes',
            handler: () => {
            // Previous page loaded
         }
         }, {
            text: 'No',
            handler: () => {
              //Page should not go back.
              //This is where i want to write code,if the user clicks 
              No and the back button function should be disabled.
              //Only when the user presses Yes,the page will go to 
              previous.
              }
            }
         ]
      });
    })

I dont know how to handle when the user presses no,i.e.Disable the back button function or event.


Solution

  • Finally i solved the issue.As the event emitted from the backButton is an promise.If I dont need to go back,i just reject that promise.

        this.platform.backButton.subscribe(()=> {
             const alert = await this.alertController.create({
             header: 'Confirm!',
             message: 'Do you want to go back!!!',
             buttons: [
             {
                text: 'Yes',
                handler: () => {
                // Previous page loaded
             }
             }, {
                text: 'No',
                handler: () => {
                reject()
                  }
                }
             ]
          });
        })