How to add ionic back button

The ionic back button element allows us to navigates back to the previous page or exit in the app’s history upon click. It is smart enough to know what to render based on the mode and when to show based on the navigation stack. We can also control mobile like Android device native back button.

In this articles, we’ll explore how to used ionic back button element with and without text and icon. We will add confirm button on exist Android application when we click on mobile device back button.

Setting up Ionic back button

With the release of ionic version 4, the Ionic framework no longer limited to angular. Ionic allows us to create ionic projects in different front-end frameworks like Angular, Vue, and React. Let first create a blank Ionic Angular project to demonstrate ionic back button.

ionic start backButtonApp blank --type=angular
ionic generate page about
ionic generate page contact

The above command will create an ionic project, add a new page about, contact, and set routing for us.

Ionic back button example

We can change and control what to display in the back button, we can use the text and icon properties. Here is a screenshot of the slot attribute used ionic back button. The slot can be left or right and by default, it is left.

Ionic back button

Let add back button for about page template.

<ion-header>
  <ion-toolbar>
    <ion-title>About</ion-title>
    <ion-buttons slot="start">
      <ion-back-button></ion-back-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

Let add the slot right attribute for the contact page template.

<ion-header>
  <ion-toolbar>
    <ion-title>Contact Page</ion-title>
    <ion-buttons slot="end">
      <ion-back-button></ion-back-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

Ionic back button with text and icon

Ionic back button allow us to add our own icon image instead of default icon. Here in both our about and contact page we have add different icon and text in ionic back button. Here is screenshot of ionic back button custom icon and text.

Ionic back button icon and text

We can see that we have a home icon undo and a home icon on the contact page. You can use an ionic icon for the icon of your choice.

Ionic back button defaultHref attribute

The ionic back button has defaultHref attribute that allows us to navigate to a specific page when there is no history of going back to the previous page. If we want to set the default to navigate the page to home, then we need to use defaultHref attribute in the Ionic back button. Here is the code to set default navigation to home.

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button text="Home-page" icon="home" defaultHref="home">
      </ion-back-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

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.

How to disabled hardware back button in Android

We will use @HostListener to listen to the Ionic back button event. To demonstrate how to disable the hardware back button on the specific page, let’s used @HostListener and add the following code in the about.page.ts file.

import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'app-about',
  templateUrl: './about.page.html',
  styleUrls: ['./about.page.scss'],
})
export class AboutPage  {

  constructor() { }

  @HostListener('document:ionBackButton', ['$event'])
  overrideHardwareBackAction(event: any) {
    event.detail.register(100, async () => {
      event.stopImmediatePropagation();
      event.stopPropagation();
      event.preventDefault();
    });
  }
}

How to add confirm alert on Ionic back button

We have used Cordova to perform confirm alert when exiting from the application using the hardware back button. For PWA you need to use the Ionic capacitor plugin to exit the application. Here is a screenshot of our confirm exit ion Android.

Ionic back button exit confirm

To use ionic splash and status bar in ionic Cordova Android, we need to install both splash and status bar by running the following command.

ionic cordova plugin add cordova-plugin-splashscreen
npm install @ionic-native/splash-screen

ionic cordova plugin add cordova-plugin-statusbar
npm install @ionic-native/status-bar --save

npm install --save @ionic-native/core

Now let’s edit the app.component.ts file to add confirm alert and when to exit our application.

import { Component } from '@angular/core';
import { Platform, AlertController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { Location } from '@angular/common';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class AppComponent {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,

    private location: Location,
    public alertCtrl: AlertController
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });


    this.platform.backButton.subscribeWithPriority(10, (processNextHandler) => {
      if (this.location.isCurrentPathEqualTo('/home')) {
        this.confirmExitApp();
        processNextHandler();
      } else {
        this.location.back();
      }
    });

  }

  async confirmExitApp() {
    const alert = await this.alertCtrl.create({
      header: 'Confirmation Exit',
      message: 'Are you sure you want to exit ?',
      backdropDismiss: false,
      cssClass: 'confirm-exit-alert',
      buttons: [{
        text: 'Stay',
        role: 'cancel',
        handler: () => {
          console.log('Application exit  handler');
        }
      }, {
        text: 'Exit apps',
        handler: () => {
          navigator['app'].exitApp();
        }
      }]
    });

    await alert.present();
  }

}

Conclusion
In this article, we have explored how to use the ionic back button element in our application. Also, demonstrate how to use the ionic back button with icons and text. We have used how to add confirm from a user when we click a few times on the Android back button.

Related posts

Spread the love

Leave a Comment

Your email address will not be published.

Scroll to Top