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).
navCtrland that caused other issues so that I resorted to havingrouteronly. I might try again though since the issue I have now is more severe than the other.