Understanding Ionic 2 navigation -- Words (1846)

Ionic2 Ionic
Ionic 2 navigation

Ionic 2 uses a navigation stack for implementing navigation between pages .You can simply think about a stack of pages ,one page on top of another page .

In a stack ( computer data structure ) you can only access the element on top .In ionic 2 terminology this means you can only view the page on top of the navigation stack so to navigate to another page you need to do one of these two actions :

  • 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 ) .

So by only understanding these two stack concepts you can understand the Ionic 2 navigation system :

  • When you navigate to a page ,you are pushing the page on top of the stack .
  • When you navigate from a page ,you are popping the page from the top of the stack .

You can understand more about the stack data structure from this Wikipedia link

Getting started with Ionic 2 navigation


Now ,that we have understood the theory behind Ionic 2 navigation system .lets see how to implement it ,don't worry you don't have to implement a stack by yourself ,Ionic 2 have already done that for you .You can easily accomplish navigation by using the NavController component alongside many other components .

If you have already generated an Ionic 2 project with some pages ,you have probably seen the NavController injected into every page constructor so you don't have to do anything else except navigating but how ?

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

Now lets see each of these components by example so we can understand when and where to use each of them .

We will start by generating a new Ionic 2 project ( based on blank template ) so go ahead and execute the following commands in your terminal or command prompt .

ionic start ionic-2-navigation blank --v2

The blank template has only one page ,the HomePage so lets first add some other pages so go ahead and navigate inside your project folder and use ionic g page generator to quickly create some new pages

cd ionic-2-navigation 
ionic g page about 
ionic g page contact 

You need to add these two pages to your app.module.ts .To do that ,simply open src/app/app.module.ts file and add the two pages to declarations and entryComponents arrays after importing them .

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';

@NgModule({
declarations: [
    MyApp,
    HomePage,
    AboutPage,
    ContactPage
],
imports: [
    IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
    MyApp,
    HomePage,
    AboutPage,
    ContactPage
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}

How to use NavController ?


Now we are ready to add a simple navigation ,lets add code to be able to navigate from our home page to either our about or contact page by clicking on some buttons .

Open app/src/pages/home/home.ts and do the following steps :

  • Import the two page components
  • Add two methods ,gotoAbout() and gotoContact()

Importing the two page components

import { AboutPage } from '../about/about';
import { ContactPage } from '../contact/contact';

Adding methods for navigation

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

constructor(public navCtrl: NavController) {

}

public gotoAbout(){
    this.navCtrl.push(AboutPage);
}

public gotoContact(){
    this.navCtrl.push(ContactPage);
}

}
As you can see we navigate to another page by using the push() method of NavController which is injected via the page constructor and becomes available from this.navCtrl object .
The NavController is already and imported for us and injected by the Ionic CLI page generator but if you are creating a page manually you need to import the NavController service from 'ionic-angular' and inject it via component constructor to be able to use it .
To navigate to another page ,first we import and then we use the NavController push method which takes the target page/component as a parameter .


Next we need to bind the two methods to two buttons on component view (home.html) .Open src/pages/home/home.html and add two buttons

<button ion-button (click)="gotoAbout();">Go to about</button>

<button ion-button (click)="gotoContact()">Go to contact</button>

Lets add a back button to our about and contact pages

Open src/pages/about/about.ts and add a goBack() method :

goBack(){
    this.navCtrl.pop();
} 

Then bind it to a button in the corresponding component view

<button ion-button (click)="goBack()">Go back</button>

Do the same for contact page .

So by using the NavController service we can navigate between pages via two methods push() and pop() which respectively pushs a page to navigation stack thus making it visible ,and pops a page from navigation stack to make it disappear so the previous page on stack becomes on top ( visible ) .

The next service we are going to see is NavParams which allows us to pass parameters between pages when navigating .

Using NavParams


In many situations we need to pass parameters from one page to another for example from a list page to a detail page .Ionic 2 has made this also as easy as navigating with NavController .

You can pass parameters with the push() method of NavController as the second parameter of the method but to retrieve them you need to use the NavParams service so lets see how to do it with an example .

Again open src/pages/home/home.ts and add modify gotoAbout() method like this :

gotoAbout(){ this.navCtrl.push(this.aboutPage,{param1 : "hello" , param2 : "world"}); }

You pass parameters as JavaScript object to the second parameter of push() method .
You can name a parameter whatever you want ,but of course ,it needs to be a valid TypeScript keyword

We need now to get these parameters in our about page ,start by opening src/pages/about/about.ts then follow the steps

  • Import NavParams from 'ionic-angular'
  • Inject the service via component constructor
  • Use the get method or data attribute of NavParams instance to retrieve values

Importing NavParams :

import { NavParams } from 'ionic-angular';

Injecting service and retrieving parameters

@Component({
selector: 'page-about',
templateUrl: 'about.html'
})
export class AboutPage {
private param1 : string ;
private param2 : string ;
private allParams ;
constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.param1 = this.navParams.get("param1");
    this.param2 = this.navParams.get("param2");
    this.allParams = this.navParams.data ;
}

ionViewDidLoad() {
    console.log('ionViewDidLoad AboutPage');
}

goBack(){
    this.navCtrl.pop();
}

}
You can find more information about NavParams service on its official docs

How to use NavPush and NavPop ?


Ionic 2 provides two other services which allow you to accomplish navigation but this time declaratively i.e inside page components views .

NavPush is the equivalent to push() method of NavController .
NavPop is the equivalent to pop() method of NavController

Lets take now an example to understand how to use them .Open /src/pages/home/home.ts and /src/pages/home/home.html

  • Add two instance variables to HomePage class ,aboutPage and contactPage to hold AboutPage and ContactPage instances
  • Add buttons with navPush and navPop attributes to home.html

Adding instance variables

export class HomePage {
    public aboutPage = AboutPage;
    public contactPage = ContactPage;
    public myParams = {
        param1 : "Hello",
        param2 : "World"
    };

Adding buttons

<button ion-button [navPush]="aboutPage">Go to about </button>
<button ion-button [navPush]="contactPage">Go to contact</button>

What if you want to pass parameters ?

This is also easy you just to use navParams property :

<button ion-button [navPush]="aboutPage" [navParams]="params">Go to about </button>

But make sure to add a member variable (myParams) ,which holds all parameters you want to pass, to HomeClass

For using navPop you just add it to a button without any value

    <button ion-button navPop>Go back</button>

and that is it ,you have a quick way to add a back button to your page without much code .

So what/when to use NavController or NavPush/NavPop ?
Both services can be used to add navigation so it depends on your preferences and needs but if you want a quick declarative way to add navigation use NavPush and NavPop .Otherwise if you want more control and the ability to add actions before or after navigation use NavController .

How to use Nav component ?


Nav is another declarative equivalent of NavController which allows you to set the root page from HTML views .

In your generated project based on the blank template you already have HomePage set as a root page .

If you open src/app/app.html ,the view associated with the root app component ,you are going to find

<ion-nav [root]="rootPage"></ion-nav>

In src/app/app.component.ts ,rootPage is set to HomePage

@Component({
templateUrl: 'app.html'
})
export class MyApp {
    rootPage = HomePage;

You can also set the root page using NavController setRoot() method

this.navCtrl.setRoot(HomePage);

Navbar


A Navbar is the navigational toolbar which you find on top of your app pages with a back button .A Navbar may contain a title , buttons ,a segment and a search bar .

Our blank demo already have a Navbar in home.html

<ion-header>
<ion-navbar>
    <ion-title>
    Ionic Blank
    </ion-title>
</ion-navbar>
</ion-header> 

So lets add some buttons to our Navbar

<ion-header>
    <ion-navbar>
        <ion-title>
            Ionic 2 navigation demo
        </ion-title>
    </ion-navbar>
    <ion-buttons end>
        <button ion-button icon-only (click)="openModal()">
            <ion-icon name="options"></ion-icon>
        </button>
    </ion-buttons>        
</ion-header> 

Conclusion


We have seen the different components/services offered by Ionic 2 to allow developers to easily add navigation between pages and set root page components .

Ionic 2 has also other components to add advanced types of navigation such as Menu and Tab components which offer quick and easy ways to add menus and tabs .




mrnerd is a Web Entrepreneur & Developer, Digital Marketer and a Passionate Blogger. He writes about software and website development,money making tips and SEO etc.. He is a tech addict and a computer geek with a lot of hobbies.