Page Navigation in Ionic app

Ionic 2 uses a navigation stack for implementing navigation between pages .A navigation stack is exactly what it sounds like, a simple stack, where we push new pages onto the top of the stack, which takes us forwards in the app and shows a back button. To go backwards, we pop the top page off.

Ionic’s navigation stack is stored in and controlled by the NavController class. By injecting this class into a @Page, you can manipulate the navigation stack. Adding items to the stack uses a push method and removing items from a stack uses a pop method, very similar to an array in javascript.

  • Push the page on the stack ,in this case it becomes on top because pushing on stack means putting the element at the top .
  • Pop a page(s) until your target page becomes on the top but this means your page needs to be already existing on navigation stack which only means you have navigated to it before .This is how Ionic 2 implements the back action button (by popping the current page from the navigation stack ) .

The NavController component exposes many methods so you can control the navigation stack with all ease but NavController is not the only available component for navigation ,there are other components :

  • NavParams
  • NavPop
  • NavPush
  • Nav
  • NavBar

The current page is the last one in the array, or the top of the stack if we think of it that way. Pushing a new page onto the top of the navigation stack causes the new page to be animated in, while popping the current page will navigate to the previous page in the stack.

Injecting NavController

Behind the scenes, when Ionic instantiates a new NavController, it creates an injector with NavController bound to that instance (usually either a Nav or Tab) and adds the injector to its own providers.

import { NavController } from 'ionic-angular';
class MyComponent {
constructor(public navCtrl: NavController) {
  }
}

Navigating from the Root component

you can use @ViewChild to get an instance of the Nav component, which is a navigation controller (it extends NavController):

import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
template: '<ion-nav #myNav [root]="rootPage"></ion-nav>'
})
export class MyApp {
@ViewChild('myNav') nav: NavController
public rootPage = TabsPage;
   // Wait for the components in MyApp's template to be initialized
// In this case, we are waiting for the Nav with reference variable of "#myNav"
ngOnInit() {
// Let's navigate from TabsPage to Page1
this.nav.push(Page1);
}
}