Need Help With Angular Development?

Work with our skilled Angular developers to accelerate your project and boost its performance.

Hire Angular Developers

Support On Demand!

In Angular, navigation between pages is handled using the Angular Router.
But before navigating, routes must be registered in the Angular Router using forRoot or forFeature.

Using forRoot() (Main Routing Module)

Define routes in app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' }
];

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

Using forFeature() (Feature Modules for Lazy Loading)

For modular applications, lazy-loaded feature modules should define their own routing using forFeature():

@NgModule({
  imports: [RouterModule.forFeature([{ path: 'feature', component: FeatureComponent }])],
  exports: [RouterModule]
})
export class FeatureRoutingModule {}

Below are different methods to navigate between pages effectively.

1. Navigating Using routerLink (Template-Based Navigation)

Use the routerLink directive to navigate between pages via templates.

Home
About

2. Navigating Using navigate()

This method is used for dynamic navigation inside TypeScript. We can pass an array of path segments using navigate().
To use the navigate method, import the Router service and inject it into the component.

import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-example',
  templateUrl: './example.component.html'
})
export class ExampleComponent {
  constructor(private router: Router) {}
  goToAbout() {
    this.router.navigate(['/about']);
  }
}

Html file:

3. Navigating Using navigateByUrl()

Used for redirections where the route is a complete string.

this.router.navigateByUrl('/about');

Note: Handling Navigation Promises for Lint Compliance

Both this.router.navigate() and this.router.navigateByUrl() return a Promise, but they are often used without handling the result. To ensure proper lint compliance and avoid unhandled promise issues, it’s best to handle them explicitly.

Handling navigate() with .then()

this.router.navigate(['/about']).then(success => {
  console.log(success ? 'Navigation successful' : 'Navigation failed');
}).catch(err => console.error('Navigation error:', err));

Handling navigateByUrl() with .then()

this.router.navigateByUrl('/about').then(success => {
  console.log(success ? 'Navigation successful' : 'Navigation failed');
}).catch(err => console.error('Navigation error:', err));

Handling these promises is not mandatory for simple navigation, but it’s a good practice.

4. Navigating with Route Parameters

Used when the route has parameters and needs to pass it while navigating.

Example route:

const routes: Routes = [
  { path: 'user/:id', component: UserComponent }
];

Now to navigate to above route,

this.router.navigate(['/user', 123]); // Navigates to /user/123

Navigating with Query Parameters:

Query parameters allow passing additional information with the route.

this.router.navigate(['/user'], { queryParams: { name: 'John', age: 30 } });

Key difference between navigate() and navigateByUrl():

  • navigate() is used when dealing with route/query parameters or dynamic paths.
  • navigateByUrl() is used for absolute navigation when the full URL is known in advance.

Related Q&A