Ram
Ram

Reputation: 611

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.

Upvotes: 1

Views: 5365

Answers (2)

Ram
Ram

Reputation: 611

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()
              }
            }
         ]
      });
    })

Upvotes: 2

Sivaramakrishnan
Sivaramakrishnan

Reputation: 739

Try this way to prevent the back button

this.platform.backButton.subscribeWithPriority(9999, () => {
      this.dismiss();
    });

Upvotes: 0

Related Questions