← All articles

[Ionic Angular] Replicating ion-back-button Behavior in Code

How to programmatically pop the navigation stack or navigate to defaultHref, matching the logic built into ion-back-button.

Published
[Ionic Angular] Replicating ion-back-button Behavior in Code cover image

<ion-back-button><ion-back-button> is handy, is it not?

  • You can pop from the destination back to the source
  • With a defaultHref attribute, you can set a fallback when there is no history, and still pop back when opening the route directly
  • When a previous page exists (history.back() works) and it differs from defaultHref, the previous page takes priority

A single component handles all of this branching and shows a back button, which makes Ionic development much easier. The one problem is when you want to pop programmatically—for example, after a delete finishes, you want to pop automatically without the user pressing the back button.

When you only push from one place, the code is simple:

  constructor(
    private navCtrl: NavController,
  ) {}

  pop() {
    this.navCtrl.navigateBack('[return URL]');

    // The following behaves the same way
    // this.navController.setDirection('back');
    // this.router.navigateByUrl('[return URL]');
  }

That is enough. However, when multiple pages can navigate in and the return destination is not fixed, reproduce ion-back-button logic in code. You can write it like this:

  public backButtonMethod(routerOutlet: IonRouterOutlet, navCtrl: NavController, defaultHref: string): void {
    if (routerOutlet && routerOutlet.canGoBack()) {
      navCtrl.setDirection('back');
      routerOutlet.pop();
    } else if (defaultHref != null) {
      navCtrl.navigateBack(defaultHref);
    }
  }

First, IonRouterOutlet.canGoBack() tells you whether pop() is possible. If it is, pop back with pop(). If not, use defaultHref as the return destination.

Now you can replicate ion-back-button behavior in code. Simple, right?

See you next time.