Routing
Router — Basics
Single Page Navigation
💡 Angular Router ek GPS navigation system hai SPA (Single Page Application) ke andar — URL badalta hai, lekin poora page reload NAHI hota, sirf SPECIFIC content area update hota hai, jaise ek app ke andar "screens" badalna, bina app band kiye.
Angular Router URL-based navigation deta hai SPAs mein — Routes array (path → component mapping) define karte ho. <router-outlet></router-outlet> template mein wo JAGAH hai jaha MATCHED component render hota hai. routerLink directive navigation links banata hai (anchor tags ki jagah, page reload avoid karne ke liye).
// app.routes.ts:
import { Routes } from '@angular/router';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'users', component: UserListComponent },
{ path: '**', component: NotFoundComponent } // wildcard — koi match na ho to
];
// Template mein:
// <nav>
// <a routerLink="/">Home</a>
// <a routerLink="/about">About</a>
// </nav>
// <router-outlet></router-outlet> — matched component yaha render hoga🧭
Angular Router ek GPS navigation system hai SPA (Single Page Application) ke andar — URL badalta hai, lekin poora page reload NAHI hota, sirf SPECIFIC content area update hota hai, jaise ek app ke andar "screens" badalna, bina app band kiye.
1 / 6
⚡ Quick Recap
- Routes array = path → component mapping
- <router-outlet> = matched component yaha render hota hai
- routerLink = navigation, page reload ke bina (href ki jagah)
On this page (2 subtopics)
routerLinkActive directive automatically ek CSS class add karti hai jab uska routerLink CURRENT active route ho — navigation menus mein "current page" ko highlight karne ke liye bahut common.
<!-- <nav>
<a routerLink="/" routerLinkActive="active-link">Home</a>
<a routerLink="/about" routerLinkActive="active-link">About</a>
</nav> -->
/* CSS: */
/* .active-link { font-weight: bold; color: blue; } */Tip: routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" home link ke liye zaroori hai — bina exact: true, "/" route HAMESHA active dikhega (kyunki har URL "/" se shuru hota hai), chahe koi doosra page ho.
Router service se CODE se navigate kar sakte ho (jaise form submit hone ke baad redirect) — routerLink template ke liye hai, Router.navigate() component logic ke liye.
import { Router } from '@angular/router';
export class LoginComponent {
constructor(private router: Router) { }
onLoginSuccess() {
this.router.navigate(['/dashboard']);
// ya query params ke saath:
// this.router.navigate(['/search'], { queryParams: { q: 'angular' } });
}
}Tip: Programmatic navigation especially useful hai CONDITIONAL redirects ke liye — jaise "agar login successful, dashboard par bhejo, warna error dikhाओ" — ye template mein (routerLink se) directly express nahi ho sakta.