🚦 Mastering Routing in Angular 19: A Developer’s Guide

Routing is a core feature of Angular that makes navigation seamless within single-page applications. Whether you’re building a small app or an enterprise-grade solution, Angular 19’s routing module gives you the power to create clean, dynamic, and scalable navigation systems.

In this guide, I’ll walk you through the essentials of Angular routing—everything from basic setup to advanced features like lazy loading, route guards, and animations.


📁 Setting Up Routing in Angular 19

Start by generating a new Angular project with routing support enabled:

ng new my-angular-app --routing
cd my-angular-app

This creates an app-routing.module.ts file for managing your app’s route definitions.


🛣️ Defining Routes

Inside app-routing.module.ts, set up your route configuration using the Routes array:

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

const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '**', component: PageNotFoundComponent } // 404 fallback
];

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

📝 Notes:

  • path: '': Default route (usually your homepage).
  • path: 'about': Navigates to the About page.
  • path: '**': Wildcard to catch unknown routes and show a 404.

🔗 Adding Navigation Links

Use Angular’s routerLink directive to create links between components:

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

<!-- Render the matched component -->
<router-outlet></router-outlet>

Highlight Active Links

To style the currently active route:

<a routerLink="/" routerLinkActive="active">Home</a>
<a routerLink="/about" routerLinkActive="active">About</a>

Then define the .active class in your CSS.


📍 Navigating Programmatically

Angular’s Router service lets you navigate through code:

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

@Component({
selector: 'app-home',
template: `<button (click)="goToAbout()">Go to About</button>`
})
export class HomeComponent {
constructor(private router: Router) {}

goToAbout() {
this.router.navigate(['/about']);
}
}

🧭 Route Parameters

Need dynamic values in your URL? Use route parameters.

Define Route with Parameter

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

Access Parameter in Component

import { ActivatedRoute } from '@angular/router';

export class ProductComponent implements OnInit {
productId!: string;

constructor(private route: ActivatedRoute) {}

ngOnInit() {
this.productId = this.route.snapshot.paramMap.get('id')!;
}
}

⚙️ Using Query Parameters

Query parameters are great for optional filters or settings:

this.router.navigate(['/product', 101], { queryParams: { discount: 10 } });

To retrieve them:

this.route.queryParams.subscribe(params => {
console.log(params['discount']); // Output: 10
});

📦 Lazy Loading Modules

Lazy loading improves performance by loading modules only when needed.

Example Route

const routes: Routes = [
{
path: 'dashboard',
loadChildren: () =>
import('./dashboard/dashboard.module').then(m => m.DashboardModule)
}
];

Make sure the DashboardModule has its own dashboard-routing.module.ts and properly configured routes.


🔐 Protecting Routes with Guards

Guards restrict access to certain routes—perfect for authentication.

Generate a Guard

ng generate guard auth

Sample Auth Guard Logic

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}

canActivate(): boolean {
const isLoggedIn = !!localStorage.getItem('user');
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}

Apply Guard to Route

const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
];

🎞️ Bonus: Route Animations

Want to add smooth transitions between routes? Use Angular’s animation features.

import { trigger, transition, style, animate } from '@angular/animations';

@Component({
selector: 'app-home',
template: `<h1 [@fadeIn]>Welcome Home</h1>`,
animations: [
trigger('fadeIn', [
transition(':enter', [
style({ opacity: 0 }),
animate('500ms', style({ opacity: 1 }))
])
])
]
})
export class HomeComponent {}

This adds a fade-in animation when the component loads.


✅ Final Thoughts

Routing in Angular 19 is powerful, flexible, and essential for building scalable single-page applications. By learning how to configure routes, use parameters, lazy load modules, protect pages, and enhance transitions, you’ll have everything you need to craft a smooth navigation experience.

Got questions about advanced routing patterns, nested routes, or route resolvers? Drop a comment or reach out—I’d love to help. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *