Navigation
For most apps, having some sort of route is often required. In this section we will cover how routing works in this app built with Ionic and Angular.

Importance of Navigation

Navigation is one of the most important parts of an app. Solid navigation patterns help us achieve great user experience while a great router implementation will ease the development process and at the same time will make our apps discoverable and linkable.
As the new Ionic position itself as the best tool to build Progressive Web Apps, and the Discoverable and Linkable principles are fundamental to PWAs, it is clear why the new Ionic Navigation relies on the Angular Router.
We have created a detailed post about Navigation in Ionic and Angular covering many use cases. If you want to learn more about navigation, I strongly recommend you check it out.

Angular Router

The Angular Router is a solid, URL based navigation library that eases the development process dramatically and at the same time enables you to build complex navigation structures.
In addition, the Angular Router is also capable of Lazy Loading modules, handle data through route with Route Resolvers, and handling Route Guards to fine tune access to certain parts of your app.
The Angular Router is one of the most important libraries in an Angular application. Without it, apps would be single view/single context apps or would not be able to maintain their navigation state on browser reloads.
With Angular Router, we can create rich apps that are linkable and have rich animations (when paired with Ionic of course).
This Ionic 5 starter app template features many different examples of navigation within an Ionic 5 app such as: Tabs, Side Menu, Lazy Loading and Angular Resolvers.
If you are new to Angular Router I strongly recommend you to read this guide.
We can use the routerLink directive to navigate to between routes. For example, in the following code, when we press the button we will navigate to the Sign Up page.
1
<ion-button [routerLink]="['/auth/signup']">
2
Sign Up!
3
</ion-button>
Copied!
RouterLink works on a similar idea as typical href, but instead of building out the URL as a string, it can be built as an array, which can provide more complicated paths.

Lazy Loading

Normally when a user opens a page, the entire page’s contents are downloaded and rendered in a single go. While this allows the browser or app to cache the content, there’s no guarantee that the user will actually view all of the downloaded content.
So, that's where Lazy Loading plays an important role, instead of bulk loading all the content at once, it can be loaded when the user accesses a part of the page that requires it. With lazy loading, pages are created with placeholder content which is only replaced with actual content when the user needs it.
Lazy loading sounds like a complicated process, but actually is very straight forward. Conceptually, we’re taking one segment of code, a chunk, and loading it on demand as the app requests it. This is a very framework agnostic take on things, and the finer details here come in the form of NgModules for Ionic apps. NgModules are the way we can organize our app’s pages, and separate them out into different chunks.
You can read more about Lazy Loading routes with Ionic and Angular, or you can see the following code example:
src/app/app-routing.module.ts
1
import { NgModule } from '@angular/core';
2
import { Routes, RouterModule } from '@angular/router';
3
4
const routes: Routes = [
5
{ path: '', redirectTo: '/walkthrough', pathMatch: 'full' },
6
{ path: 'walkthrough', loadChildren: './walkthrough/walkthrough.module#WalkthroughPageModule' },
7
{ path: 'getting-started', loadChildren: './getting-started/getting-started.module#GettingStartedPageModule' },
8
{ path: 'auth/login', loadChildren: './login/login.module#LoginPageModule' },
9
{ path: 'auth/signup', loadChildren: './signup/signup.module#SignupPageModule' },
10
{ path: 'auth/forgot-password', loadChildren: './forgot-password/forgot-password.module#ForgotPasswordPageModule' },
11
{ path: 'app', loadChildren: './tabs/tabs.module#TabsPageModule' },
12
{ path: 'contact-card', loadChildren: './contact-card/contact-card.module#ContactCardPageModule' },
13
{ path: 'forms-and-validations', loadChildren: './forms/forms.module#FormsPageModule' },
14
{ path: 'filters', loadChildren: './filters/filters.module#FiltersPageModule' },
15
{ path: 'page-not-found', loadChildren: './page-not-found/page-not-found.module#PageNotFoundModule' },
16
{ path: '**', redirectTo: 'page-not-found' }
17
];
18
@NgModule({
19
imports: [RouterModule.forRoot(routes)],
20
exports: [RouterModule]
21
})
22
export class AppRoutingModule {}
23
Copied!
This code is from our AppRoutingModule where all the app routes are defined (except the tabs routes).

Resolvers

If you were using a real world API, there might be some delay before the data to display is returned from the server. You don't want to display a blank component while waiting for the data.
It's preferable to pre-fetch data from the server so it's ready the moment the route is activated. This also allows you to handle errors before routing to the component. There's no point in navigating to a route if we don't have any data to display.
You want to delay rendering the routed component until all necessary data have been fetched and for this you need a resolver.
In this Ionic app we use resolvers for each route that needs to load data. Let's see an example of the NotificationsResolverused to prefetch the data for the NotificationsPage.
BASIC version
PRO version
src/app/notifications/notifications.resolver.ts
1
import { Injectable } from '@angular/core';
2
import { Resolve } from '@angular/router';
3
4
import { NotificationsService } from './notifications.service';
5
6
@Injectable()
7
export class NotificationsResolver implements Resolve<any> {
8
9
constructor(private notificationsService: NotificationsService) { }
10
11
resolve() {
12
return this.notificationsService.getData();
13
}
14
}
15
Copied!
src/app/notifications/notifications.resolver.ts
1
import { Injectable } from '@angular/core';
2
import { Resolve } from '@angular/router';
3
4
import { NotificationsService } from './notifications.service';
5
6
@Injectable()
7
export class NotificationsResolver implements Resolve<any> {
8
9
constructor(private notificationsService: NotificationsService) { }
10
11
resolve() {
12
// Base Observable (where we get data from)
13
const dataObservable = this.notificationsService.getData();
14
return { source: dataObservable };
15
}
16
}
Copied!
When using resolvers, we have to add them to the route definition like this:
src/app/notifications/notifications.module.ts
1
RouterModule.forChild([
2
{
3
path: '',
4
component: NotificationsPage,
5
resolve: {
6
data: NotificationsResolver
7
}
8
}
9
])
Copied!

Tabs Navigation

To customize the tabs navigation options go tosrc/app/tabs/tabs.page.html
The Angular Router provides Ionic with the mechanism to know what components should be loaded, but the heavy lifting is actually done by the Ion tabs component.
In the following code we have our TabsPageRoutingModule which contains all the routes under the tabs.
tabs navigation
If you go back to our AppRoutingModule , your will find that we have a path 'app' which loads the TabsPageModule.
app-routing.module.ts
1
{
2
path: 'app',
3
loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
4
},
Copied!
On this Ionic app, we named the path that has the tabs “app”, but the name of the paths are open to be changed. They can be named whatever fits your app.
In that route object, we can define a child route as well. In this example, one of the top level child route is "categories" and can load additional child routes.
Change the following file to add your own pages to the tabs navigation.
src/app/tabs/tabs.router.module.ts
1
import { NgModule } from '@angular/core';
2
import { RouterModule, Routes } from '@angular/router';
3
import { HttpClientModule } from '@angular/common/http';
4
import { TabsPage } from './tabs.page';
5
6
const routes: Routes = [
7
{
8
path: '',
9
component: TabsPage,
10
children: [
11
{
12
path: 'categories',
13
children: [
14
{
15
path: '',
16
loadChildren: () => import('../categories/categories.module').then(m => m.CategoriesPageModule)
17
},
18
{
19
path: 'fashion',
20
loadChildren: () => import('../fashion/listing/fashion-listing.module').then(m => m.FashionListingPageModule)
21
},
22
{
23
path: 'fashion/:productId',
24
loadChildren: () => import('../fashion/details/fashion-details.module').then(m => m.FashionDetailsPageModule)
25
},
26
{
27
path: 'food',
28
loadChildren: () => import('../food/listing/food-listing.module').then(m => m.FoodListingPageModule)
29
},
30
{
31
path: 'food/:productId',
32
loadChildren: () => import('../food/details/food-details.module').then(m => m.FoodDetailsPageModule)
33
},
34
{
35
path: 'travel',
36
loadChildren: () => import('../travel/listing/travel-listing.module').then(m => m.TravelListingPageModule)
37
},
38
{
39
path: 'travel/:productId',
40
loadChildren: () => import('../travel/details/travel-details.module').then(m => m.TravelDetailsPageModule)
41
},
42
{
43
path: 'deals',
44
loadChildren: () => import('../deals/listing/deals-listing.module').then(m => m.DealsListingPageModule)
45
},
46
{
47
path: 'deals/:productId',
48
loadChildren: () => import('../deals/details/deals-details.module').then(m => m.DealsDetailsPageModule)
49
},
50
{
51
path: 'real-state',
52
loadChildren: () => import('../real-state/listing/real-state-listing.module').then(m => m.RealStateListingPageModule)
53
},
54
{
55
path: 'real-state/:productId',
56
loadChildren: () => import('../real-state/details/real-state-details.module').then(m => m.RealStateDetailsPageModule)
57
}
58
]
59
},
60
{
61
path: 'user',
62
children: [
63
{
64
path: '',
65
loadChildren: () => import('../user/profile/user-profile.module').then(m => m.UserProfilePageModule)
66
},
67
{
68
path: 'friends',
69
loadChildren: () => import('../user/friends/user-friends.module').then(m => m.UserFriendsPageModule)
70
}
71
]
72
},
73
{
74
path: 'notifications',
75
children: [
76
{
77
path: '',
78
loadChildren: () => import('../notifications/notifications.module').then(m => m.NotificationsPageModule)
79
}
80
]
81
},
82
]
83
},
84
// /app/ redirect
85
{
86
path: '',
87
redirectTo: 'app/categories',
88
pathMatch: 'full'
89
}
90
];
91
92
@NgModule({
93
imports: [RouterModule.forChild(routes), HttpClientModule],
94
exports: [RouterModule],
95
providers: [ ]
96
})
97
export class TabsPageRoutingModule {}
Copied!

Side Menu Navigation

side menu navigation
To customize the side menu go tosrc/app/app.component.html and src/app/app.component.ts
We use the ion-menu component from Ionic UI Components. You can either define the menu items in the markup or in the Component.
Let's see an example. The following code defines the Forms section of the ion-menu with two items.
With the [routerLink] you define the route where you want to navigate to when clicking the ion-item.
Remember that those routes are defined in src/app/app-routing.module.ts
The icons can be set either using Ionicons, like we do in the Form Filters option, or using custom svg icons. This template includes lots of custom and beautiful svg icons that you can use in your ionic apps.
app.component.html
1
<ion-list>
2
<ion-list-header>
3
<ion-label>Forms</ion-label>
4
</ion-list-header>
5
<ion-menu-toggle autoHide="false">
6
<ion-item [routerLink]="['/forms-and-validations']">
7
<ion-icon slot="start" src="./assets/custom-icons/side-menu/forms.svg"></ion-icon>
8
<ion-label>
9
Forms & Validations
10
</ion-label>
11
</ion-item>
12
<ion-item [routerLink]="['/forms-filters']">
13
<ion-icon slot="start" name="options-outline"></ion-icon>
14
<ion-label>
15
Filters
16
</ion-label>
17
</ion-item>
18
</ion-menu-toggle>
19
</ion-list>
Copied!
Also, other menu item options are defined as a list in the AppComponent and iterated in the html. Let's see an example.
app.component.ts
1
accountPages = [
2
{
3
title: 'Log In',
4
url: '/auth/login',
5
ionicIcon: 'log-in-outline'
6
},
7
{
8
title: 'Sign Up',
9
url: '/auth/signup',
10
ionicIcon: 'person-add-outline'
11
},
12
... // more pages
13
]
Copied!
app.component.html
1
<ion-list>
2
<ion-list-header>
3
<ion-label>Account</ion-label>
4
</ion-list-header>
5
<ion-menu-toggle autoHide="false" *ngFor="let p of accountPages; let i = index">
6
<ion-item [routerLink]="p.url">
7
<ion-icon slot="start" [name]="p.ionicIcon? p.ionicIcon: ''" [src]="p.customIcon? p.customIcon: ''"></ion-icon>
8
<ion-label>
9
{{p.title}}
10
</ion-label>
11
</ion-item>
12
</ion-menu-toggle>
13
</ion-list>
Copied!

Initial route of the application

Currently, the app starts with the walkthrough, and then follows with the authentication screens. If you would like to start your app at the Categories page, simply go to src/app/app-routing.module.ts and change this line:
{ path: '', redirectTo: '/walkthrough', pathMatch: 'full' },
for:
{ path: '', redirectTo: '/app/categories', pathMatch: 'full' },
Last modified 7mo ago