Adding an android back button in Ionic.

Here we will learn how to handle the default mobile’s back button which allows us to popup to the parent page and allow us to exit from the application when there is nothing to pop up a page.

We can achieve android mobile back button through 3rd plugins, like ionic-hardware-buttons. This approach is fine for a project which had only a few pages but if our project has lot of pages, then we have to add

    public onBackButton() {
        alert('Back button pushed!');
        return false;

To all the page we have to add above code in typescript to handle back button.

There is another approach, without 3rd plugins. The Platform service can be used to get information about your current device and orientation.  We can uses platform.registerBackButtonAction(fn, priority)

The back button event is triggered when the user presses the native platform’s back button, also referred to as the “hardware” back button. This event is only used within Cordova apps running on Android and Windows platforms. This event is not fired on iOS since iOS doesn’t come with a hardware back button in the same sense an Android or Windows device does.

Registering a hardware back button action and setting a priority allows apps to control which action should be called when the hardware back button is pressed. This method decides which of the registered back button actions has the highest priority and should be called.

import { App, Nav, Platform, MenuController, Events, AlertController } from 'ionic-angular';

  templateUrl: 'app.html'
export class RupeeBooks {
  @ViewChild(Nav) nav: Nav;

    private app: App,
    private platform: Platform,
  ) {
    platform.ready().then(() => {

    platform.registerBackButtonAction(() => {
      let nav = app.getActiveNavs()[0];
      let activeView = nav.getActive();

      if ( !== 'HomePage') {
        if (nav.canGoBack())
      else {
        // Add toast or confirm code over here