Implementing sub-navigation using ion-nav in Ionic 5 (Angular)
Moving from the older version of Ionic to the Ionic 5, one thing you may stumble upon is using the ion-nav
component. Let us take a dive to see how to correctly use ion-nav for sub-navigation using ion-modal
.
Setting up the template:
Just start off by creating a component where you would house your sub-navigation and add ion-nav
in the template like this
@Component({
selector: "app-sub-navigation",
template: "<ion-nav #mySubNav ></ion-nav>",
styleUrls: []
})
class MySubNavigationComponent
Notice i’ve used a template reference variable #mySubNav
which I will use later to reference this ion-nav
. Now let us get to the actual code to play with ion-nav
and push pages/components on to the navigation stack.
1. Using Viewchild.
import {ViewChild} from "@angular/core"
@Component({
selector: "app-sub-navigation",
template: "<ion-nav #mySubNav ></ion-nav>",
styleUrls: []
})
class MySubNavigationComponent {
@ViewChild('mySubNav', {static: true}) myNav: IonNav;
constructor() {}
}
2. Update app.module.ts
import SubNavigationComponentModule from "./components/sub-navigation-component/sub-navigation-component.module.ts";
@ngModule({
imports: [SubNavigationComponentModule]
})
3. Set root page
import {ViewChild} from "@angular/core";
import Component1 from "./component1.component.ts";
@Component({
selector: 'app-sub-navigation',
template: '<ion-nav #mySubNav ></ion-nav>',
styleUrls: []
})
class MySubNavigationComponent {
@ViewChild("mySubNav", {static: true}) myNav: IonNav;
private rootPage;
private rootParams;
constructor() {
this.rootPage = Component1;
this.rootParams = {
// any parameters to pass to the component
}
}
ngOnInit() {
this.myNav.setRoot(this.rootPage, this.rootParams);
}
Notice myNav
gives us a way to use the methods provided by IonNav.
- Push Components on the nav-stack
import {ViewChild, OnInit} from "@angular/core";
import Component1 from "./component1/component1.component.ts";
import Component2 from "./component2/component2.component.ts";
@Component({
selector: "app-sub-navigation",
template: "<ion-nav #mySubNav ></ion-nav>",
styleUrls: []
})
class MySubNavigationComponent implements OnInit {
@ViewChild("mySubNav", {static: true}) myNav: IonNav;
private rootPage;
private rootParams;
constructor() {
this.rootPage = Component1;
this.rootParams = {
// any parameters to pass to the component
}
}
ngOnInit() {
this.myNav.setRoot(this.rootPage, this.rootParams);
}
private pushToNav() {
this.myNav.push(Component2, {ninjaName: 'Alpha'});
}
private popFromNav() {
this.myNav.pop()
}
}
- Accessing nav params`
import {NavParams} from "@ionic/angular";
@Component({
selector: "app-component2",
templateUrl: "./component2.component.html" ,
styleUrls: []
})
class Component2 implements OnInit {
private ninjaName: string;
constructor(private navParams: NavParams) {}
ngOnInit() {
this.ninjaName = this.navParams.get('ninjaName');
}
}