Please or Register to create posts and topics.

Ionic/Angular: Same back button behaviour on iOS, android and custom button.

How to use the same back button logic for an Android hardware back button and any custom button on the Angular page? No problem! The solution I show you in the tutorial allows you write all your navigation logic in one place and makes it work exactly the same on Android and iOS devices.



This is a continuation of the previous tutorial, so before you start reading it, I suggest reading the previous part.

To achieve the same behavior of back button on Android and iOS devices you can create default Ionic back button with custom click listener. Instead of calling default back behavior you can call performBackButtonAction of modified BackButtonService. After that, both hardware back button and back (button in navigation bar) call performBackButtonAction method giving the same behavior no matter which one you press.



<ion-header [translucent]="true">
    <ion-toolbar>
        <ion-title>
            Home
        </ion-title>
        <ion-buttons slot="start">
            <ion-back-button defaultHref="#" (click)="backButtonService.performBackButtonAction()"></ion-back-button>
        </ion-buttons>
    </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
    <ion-button routerLink="/contact">Go Contact page</ion-button>
</ion-content>

import { Component } from '@angular/core';
import { BackButtonService } from '../services/back-button.service';

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

  constructor(public backButtonService:BackButtonService) {}
}

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController, NavController, Platform, ToastController } from '@ionic/angular';

@Injectable({
  providedIn: 'root'
})
export class BackButtonService {
  private lastTimeBackButtonWasPressed = 0;
  private timePeriodToAction = 2000;

  init() {
    this.platform.backButton.subscribeWithPriority(10, async () => {
      this.performBackButtonAction();
    });
  }

  public performBackButtonAction() {
    const currentUrl = this.router.url;
    if (currentUrl === "/home") {
      // this.withAlert("Do you really want to exit?", () => {
      //   navigator['app'].exitApp();
      // })
      this.withDoublePress("Press again to exit", () => {
        navigator['app'].exitApp();
      });
    } else {
      this.navControlelr.back();
    }
  }

  async withDoublePress(message: string, action: () => void) {
    const currentTime = new Date().getTime();

    if (currentTime - this.lastTimeBackButtonWasPressed < this.timePeriodToAction) {
      action();
    } else {
      const toast = await this.toastController.create({
        message: message,
        duration: this.timePeriodToAction
      });

      await toast.present();

      this.lastTimeBackButtonWasPressed = currentTime;
    }
  }

  async withAlert(message: string, action: () => void) {
    const alert = await this.alertController.create({
      message: message,
      buttons: [{
        text: "Cancel",
        role: "cancel"
      },
      {
        text: "OK",
        handler: action
      }]
    });

    await alert.present();
  }

  constructor(private platform: Platform,
    private router: Router,
    private navControlelr: NavController,
    private alertController: AlertController,
    private toastController: ToastController) { }
}

When designing the navigation of your application you should consider that the iPhone does not know such term like "hardware back button". Alternatively, you can create custom back button in the navigation bar.

You can watch the full tutorial in YouTube: