Ionic 4 Hardware Back button Event

Ogunwole Samuel dare
2 min readSep 23, 2019

--

Ionic Hard Ware Back

Hardware compatibility is essential in any Android App. Recently i was working with Ionic 4 and the back button event of Platform is not working i try numerous solutions on StackOverflow all to no avail.

The previous hardware back button is handled out of the box with Ionic Version 3 with this syntax and works seamlessly

configureBackButton() {
this.platform.registerBackButtonAction(() => {
//your logic goes here
}
}

Today, I am going to show you how to handle this with Ionic 4 with this little logic

Install a new ionic project or use an existing one

npm install -g ionic

Then start a new Project

ionic start myApp tabs

open your app.component.ts file add this line before the constructor and import the file also

import { Platform, NavController, IonRouterOutlet } from '@ionic/angular';
import { Router } from '@angular/router';
@ViewChildren(IonRouterOutlet) routerOutlets: QueryList<IonRouterOutlet>;

Then write this method in your app.component.ts and add it to your constructor you Can name your method the way you like or your style

backButtonEvent() {
document.addEventListener("backbutton", () => {
this.routerOutlets.forEach((outlet: IonRouterOutlet) => {
if (outlet && outlet.canGoBack()) {
outlet.pop();
} else if (this.router.url === "tabs/tab1") {
navigator['app'].exitApp(); // work for ionic 4
} else if (!outlet.canGoBack()) {
navigator['app'].exitApp(); // work for ionic 4
}
});
});
}

your constructor should look like this

constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private network: Network,
private router: Router,
) {
this.initializeApp();
//method added to constructor
this.backButtonEvent();
}

The major difference between this and the previous version is we call;

document.addEventListener("backbutton", () => {
// your Logic goes here
}
}

Thank you very much for reading I hope this helps someone happy coding

--

--

Ogunwole Samuel dare
Ogunwole Samuel dare

Written by Ogunwole Samuel dare

Am Software developer who love to write javascript, I am working as Software Architect at Holiday Taxis Group Brighton United Kingdom

Responses (2)