1

I need to trigger the same function and the back button in the nav menu would trigger from code.

    <ion-buttons slot="start">
      <ion-back-button></ion-back-button>
    </ion-buttons>

I am currently using

    this.router.navigate(['/previousPage', {
        demoMode: false
    }]);

but there is a weird inconsistency with D3 on the start view that does not occur with the back button yet happens with the router. I just do not know which function the back button triggers in the background. Guess it must be something similar to navCtrl.pop ?

2
  • 1
    Have you tried this? forum.ionicframework.com/t/… Commented Mar 5, 2021 at 16:27
  • I think I did in a way, I had navCtrl and that caused other issues so that I resorted to having router only. I might try again though since the issue I have now is more severe than the other. Commented Mar 5, 2021 at 18:03

1 Answer 1

4

The best way to know these things is by taking a look at Ionic's source code. Ionic's source code is super well organised so most of the times it's super easy to find what some components do behind the scenes.

Regarding your question, this is the code of the ion-back-button directive.

Based on that, seems like Ionic uses the IonRouterOutlet if it's available or the NavController otherwise:

if (this.routerOutlet && this.routerOutlet.canGoBack()) {
  this.navCtrl.setDirection('back', undefined, undefined, this.routerAnimation);
  this.routerOutlet.pop();
  // ...
} else if (defaultHref != null) {
  this.navCtrl.navigateBack(defaultHref, { animation: this.routerAnimation });      
}

So knowing that, you can write a method that does exactly the same thing. Please take a look at this Stackblitz demo.

The most relevant part of the code is the DetailsPage:

import { Component, Optional } from "@angular/core";
import { IonRouterOutlet, NavController } from "@ionic/angular";

@Component({
  selector: "app-details",
  templateUrl: "./details.page.html",
  styleUrls: ["./details.page.scss"]
})
export class DetailsPage {
  constructor(
    @Optional() private routerOutlet: IonRouterOutlet,
    private navCtrl: NavController
  ) {}

  public goBack(): void {
    if (this.routerOutlet && this.routerOutlet.canGoBack()) {
      this.navCtrl.setDirection("back");
      this.routerOutlet.pop();
    } else {
      this.navCtrl.navigateBack("/home");
    }
  }
}

In the demo I omitted setting a custom page transition, but you can do it if you're using a custom page transition in your app.

Btw if you want to simplify that code, I guess you can just use this.navCtrl.navigateBack("/home"); directly since the NavController in Ionic 5 uses Angular's router behind the scenes (as can be seen here).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.