Angular Routing and Navigation in Single Page Applications (SPA)
Angular's Routing and Navigation system is a core feature that enables building Single Page Applications (SPAs). SPAs dynamically load content without refreshing the entire page, making the user experience smoother and faster.
Here's a breakdown of Angular Routing and Navigation in SPAs:
🔁 What is Angular Routing?
Angular Routing allows you to define how the application should navigate between different views or components based on the URL. It maps URLs to components, ensuring content is rendered dynamically within a single page.
🧱 Key Concepts
1. Routes Configuration
Defined using RouterModule.forRoot() in the app-routing.module.ts.
ts
Copy
Edit
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'products/:id', component: ProductDetailComponent },
{ path: '**', component: PageNotFoundComponent } // Wildcard route
];
2. RouterModule
You import and configure the RouterModule in your app module:
ts
Copy
Edit
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
3. RouterOutlet
A directive that marks where in the template the routed component should be displayed.
html
Copy
Edit
<router-outlet></router-outlet>
4. RouterLink
Used to navigate between routes in templates.
html
Copy
Edit
<a routerLink="/about">About</a>
To pass dynamic parameters:
html
Copy
Edit
<a [routerLink]="['/products', product.id]">View Product</a>
🚦 Programmatic Navigation
You can navigate in code using the Router service:
ts
Copy
Edit
constructor(private router: Router) {}
goToAbout() {
this.router.navigate(['/about']);
}
⚙️ Route Parameters and Query Params
Route Parameters:
ts
Copy
Edit
// URL: /products/42
this.route.snapshot.paramMap.get('id');
Query Parameters:
ts
Copy
Edit
// URL: /products?id=42
this.route.snapshot.queryParamMap.get('id');
🛡️ Route Guards
Used to control access to routes (e.g., authentication).
ts
Copy
Edit
canActivate(): boolean {
return this.authService.isLoggedIn();
}
Use in routes:
ts
Copy
Edit
{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }
🧩 Lazy Loading
Load modules only when needed to optimize performance.
ts
Copy
Edit
{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
📌 Summary
Feature Purpose
RouterModule Configures routes
router-outlet Placeholder for routed components
routerLink Declarative navigation
Router Programmatic navigation
Route Guards Protect or restrict access
Lazy Loading Performance optimization by loading modules on demand
Learn MEAN Stack Course
Read More
Understanding Middleware in Express.js
MEAN vs. MERN: Key Differences and Use Cases
🧠 Conceptual & Deep-Dive Topics in MEAN
Deploying a MEAN Stack App to the Cloud (e.g., Heroku, AWS, Vercel)
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment