Angular Navigation


What is Angular Navigation?

Angular's navigation system empowers developers to programmatically and declaratively move between parts of an application, based on user interaction or business logic.


Understanding Navigation in Angular

In Angular, navigation refers to transitioning from one route to another, either by clicking links or invoking methods in TypeScript code.

The navigation mechanism is powered by Angular's Router service and RouterLink directive.


Programmatic Navigation with Router

You can trigger navigation through code using Angular’s built-in Router class:

import { Component } from '@angular/core'; 
import { Router } from '@angular/router';  

<component>({   
       selector: 'app-dashboard',   
       template: `<button (click)="goToProfile()">Visit Profile</button>` 
}) 
export class DashboardComponent {   
      constructor(private router: Router) {}    
      
      goToProfile() {     
           this.router.navigate(['/profile']);   
      } 
} 

Pressing the button triggers router.navigate() to seamlessly redirect the user to the /profile route without a page reload.


Declarative Navigation with RouterLink

Instead of manually navigating in code, you can use the routerLink directive in HTML templates:

<a routerLink="/contact">Reach Us</a>

This creates a clickable link that updates the view without triggering a full-page reload.


Navigation with Parameters

Dynamic path segments can be routed by supplying parameters through navigate() or [routerLink] with an array-based configuration.

this.router.navigate(['/user', 42]); // Goes to /user/42
<a [routerLink]="['/user', 42]">User Details</a>

Navigating with Route Guards

Before transitioning, Angular can check route conditions using guards like CanActivate:

canActivate(): boolean {   
    return this.authService.isLoggedIn(); 
} 

This ensures users only visit routes they’re permitted to access.


Summary

  • Router Service: Navigate in TypeScript with full control.
  • RouterLink Directive: Bind routes in HTML views.
  • Dynamic Segments: Handle parameters cleanly.
  • Access Control: Use guards for safe navigation.

Prefer Learning by Watching?

Watch these YouTube tutorials to understand ANGULAR Tutorial visually:

What You'll Learn:
  • 📌 Angular Tutorial - 23 - Routing and Navigation
  • 📌 Routing and Navigation in Angular | Mosh
Previous Next