A Complete Guide to Ionic Navigation [Angular Router]

ionic-navigation-tutorial

In mobile app development, creating one screen is not enough.we need to create multiple screens and pass/share data between screens. This tutorial, we're going to using Angular Router for navigate between pages & pass the data.

We're going to use 3 methods for a navigation

  1. Using RouterLink
  2. Using navigateByUrl()
  3. Using navigate()

Goal

  • Create a simple contact app
  • Reading local JSON file
  • Pass data using RouterLink

Let's start our navigation project

ionic start navigation blank
cd navigation

Reading Local JSON

Let's create a new file called assets/contacts.json to store the user's info.

[
    {
        "id": 1,
        "name": "sundaraavel",
        "company": "codesundar.com",
        "avatar": "https://i.pravatar.cc/300"
    },
    {
        "id": 2,
        "name": "Priyaka",
        "company": "HTML Foundataion",
        "avatar": "https://i.pravatar.cc/200"
    }
]

Now using data, we can create a ListView in your home page.so that your home.page.html looks like this

<ion-content>
    <ion-list>
        <ion-item *ngFor="let c of contacts">
            <ion-avatar slot="start">
                <img src="{{c.avatar}}" />
            </ion-avatar>
            <ion-label>
                {{c.name}}
            </ion-label>
        </ion-item>
    </ion-list>
</ion-content>

Where contacts array is coming from the home.page.ts using http request

this.http.get('assets/contacts.json').subscribe((res: any) => {
    this.contacts = res;
})

Creating new page

To create a new page, we need to execute

ionic g page detail

Since we're going to use RouterLink, we need edit detail to detail/:id edit our app.routing.module.ts

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomePageModule) },
  {
    path: 'detail/:id',
    loadChildren: () => import('./detail/detail.module').then(m => m.DetailPageModule)
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Now we can add routerLink in ion-item

 <ion-item *ngFor="let c of contacts" routerLink="/detail/{{c.id}}">
 </ion-item>

When user click any of the contact, the page will navigate to detail page. To get the value of :id in detail page, we need to using ActivatedRoute

detail/detail.page.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-detail',
  templateUrl: './detail.page.html',
  styleUrls: ['./detail.page.scss'],
})
export class DetailPage implements OnInit {

  userId;
  user: any = {};

  constructor(
    private http: HttpClient,
    private route: ActivatedRoute
  ) {
    this.userId = this.route.snapshot.paramMap.get('id');
  }

  ngOnInit() {
    this.http.get('./assets/contacts.json').subscribe(res => {
      this.user = res[this.userId];
    })
  }

}

Code Explanation:

  • We have created route object from ActivatedRoute under the constructor.where route object is used for reading the params
  • Once, we received the userId, we have made the http request to local json & got the information based on :id value & assigned the result in to user variable

detail/detail.page.html

<ion-header>
    <ion-toolbar color="primary">
        <ion-buttons slot="start">
            <ion-back-button></ion-back-button>
        </ion-buttons>
        <ion-title>{{user.name}}</ion-title>
    </ion-toolbar>
</ion-header>

<ion-content>
    <div class="center">
        <img src="{{user.avatar}}">
        <h3>{{user.name}}</h3>
        <p>{{user.company}}</p>
    </div>
</ion-content>

It's same as the previous step. Instead of using the routerLink="" we can create (click) method to pass the data between pages.

<ion-item *ngFor="let c of contacts" (click)="viewDetail(c.id)">
    <ion-avatar slot="start">
        <img src="{{c.avatar}}" />
    </ion-avatar>
    <ion-label>
        {{c.name}}
    </ion-label>
</ion-item>
viewDetail(id) {
    this.router.navigateByUrl('/detail/' + id);
}

Using navigate()

In this method, we're going to use this.router.navigate() for navigate between pages.

File: app/home/home.page.html

<ion-item *ngFor="let c of contacts" (click)="usingNavigate(c.id)">
    <ion-avatar slot="start">
        <img src="{{c.avatar}}" />
    </ion-avatar>
    <ion-label>
        {{c.name}}
    </ion-label>
</ion-item>

File: app/home/home.page.ts

  usingNavigate(id) {
    this.router.navigate(['/detail'], {
      queryParams: {
        data: JSON.stringify(this.contacts[id - 1])
      }
    })
  }

File: app/detail/detail.page.ts

  constructor(
    private http: HttpClient,
    private route: ActivatedRoute
  ) {
    this.route.queryParamMap.subscribe((res: any) => {
      this.user = JSON.parse(res.params.data);
    })
  }

Explanation:

  • We have used this.route.queryParamMap to read all incoming data from the home page & assigned the inputs to this.user variable

Output

ionic-routing-tutorial

Ionic Routing Example Code

Reference