Angular Routing


What is Routing in Angular?

Routing in Angular allows users to move between views or components based on the URL path, without reloading the entire page. It dynamically swaps content using a .


Navigate Without Reloading

Angular's RouterModule enables seamless navigation across components while keeping your application a true Single Page Application (SPA).


Setting Up Angular Routing

Step 1: Import the RouterModule and define your 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: '', component: HomeComponent },   
         { path: 'about', component: AboutComponent },   
         { path: '**', redirectTo: '' } // wildcard route 
];  

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

Using the Router in Templates

In your template, use Angular’s routerLink directive for navigation and router-outlet for rendering:

<nav>   
      <a routerLink="/">Home</a>   
     <a routerLink="/about">About</a> 
</nav>  

<router-outlet></router-outlet> 

Key Concepts

  • Route Definitions: Use objects with path and component properties to map URLs to views.
  • Dynamic Segments: Routes can have parameters like /user/:id.
  • Lazy Loading: Optimize performance by loading feature modules only when needed.
  • Guards: Secure and control access with CanActivate, CanDeactivate, etc.
  • Wildcard Routes: Catch-all paths using ** for 404 handling or redirection.

Example: Dynamic Route with Parameter

{ path: 'product/:id', component: ProductDetailComponent }

And in the component:

constructor(private route: ActivatedRoute) {   
     this.route.params.subscribe(params => {     
        console.log(params['id']);   
     });
} 

Summary

Angular routing delivers a modern and flexible approach to client-side navigation. With dynamic components, parameter handling, route guards, and lazy loading, you can build feature-rich applications without breaking the SPA experience.


Prefer Learning by Watching?

Watch these YouTube tutorials to understand ANGULAR Tutorial visually:

What You'll Learn:
  • 📌 Angular Routing Tutorial | Angular Tutorial For Beginners | Angular Advanced Routing | Simplilearn
  • 📌 How to route in Angular - Learning Angular (Part 5)
Previous Next