Ionic 4 – Android Back Button disabled

In this article, we will learn how to disable the android back button. As I have tested this in android. In Ionic 3 we can easily disable the hardware back button. As in Ionic 4, we have to use a different approach.
I tried this method from a platform.

    this.platform.backButton.subscribe(() => {

    });

I don’t want to show any alert to disabled the back button. I want to disable the back button without any alert. But I don’t get any event to dismiss the back button event. So, i have used @HostListener,
Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs. This is a function decorator that accepts an event name as an argument. When that event gets fired on the host element it calls the associated function. So if we add this function to our directive class:

TypeScript
@HostListener('mouseover') onHover() {
  window.alert("hover");
}

We will use @HostListener to listen to the Ionic back button event. First, create two pages. Add first-page with a link to the second page.

<ion-button expand="block" routerLink="/second">
   Second
 </ion-button>

In the second page we add the following code in typescript to disabled hardware back button.

  /** Stop hardware back button */
  @HostListener('document:ionBackButton', ['$event'])
  overrideHardwareBackAction(event: any) {
    console.log('back button');
    event.detail.register(100, async () => {
      event.stopImmediatePropagation();
      event.stopPropagation();
      event.preventDefault();
    });
  }
Spread the love

1 thought on “Ionic 4 – Android Back Button disabled”

  1. Đỗ Tiến Đại

    thanks for your posts very much. only your solution working for me, others solution not working for me. tks you!!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top