Best Way to Do Page Navigation or Routing in Ionic

There are many ways to do page navigation or router link in an ionic angular project development. Today we will see which is/are the best way to do it so that it matches the basic concept or requirements like any other framework and acts as the simple link or hyperlink.

Let’s begin.

app-routing.module.ts

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

In the above app-routing.module.ts file you can see the sample routing paths. Here I have created a sample route that is test. We will test all the routing and page navigation tests on that URL.

Now let’s look at the various ways we can navigate our routes.

  • Declare a link in the HTML

A button or link is the most basic way to navigate to one of your defined routes.


Hello
Hello

  • Angular Router syntax for non-ionic components
 Hello
 Hello

  • Navigate Programmatically

You might also navigate dynamically from a component or service. A common use-case is when you need to wait for something async to finish, then send the user to a new page. Angular provides a Router service that we can inject into components by declaring it in the constructor.


import { Component } from '@angular/core';
import { Router } from '@angular/router'; 
@Component({ ... })
export class HomePage {  constructor(private router: Router) {}
go() {    
this.router.navigateByUrl('/test');  
}
}

So, these are the techniques that you can do use for routing in ionic angular projects. But here is a problem. In normal websites, if you right-click on any link or hyperlink it will show you the list of options like the below image.

You can see the options such as “Open link in new tab”, “Open link in new window” etc. Another thing, if you press and hold the ctrl key and click on the link it will open that link on a new tab. But in ionic the above mentioned two things will not work. And for any website these are the very basic things, without these, there is no means to use it. But do not worry! I will show you how to do it. To achieve that implement the router link like below  –

  1. Hello
  2. Hello

Keep in mind, do not use  or any other non-ionic components with href attribute. If you use href then the page will be load like a normal page otherwise, like PWA or an app.

Conclusion:

That’s all friends. You can like, share, and comment below in the comment section.

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.