Let’s
break down how to navigate through applications with routing in Angular.
🗺️ What is Angular Routing?
Routing lets you build single-page
applications (SPAs) — where navigating to different "pages"
(views) doesn’t reload the browser, it just swaps out parts of the page.
✅ Example:
http://localhost:4200/home
http://localhost:4200/about
You can assign each
of these paths to a component, and Angular will render the right one
automatically.
⚙️ Step-by-Step: Set Up Routing in Angular
✅
1. Enable Routing in Your App
If you didn’t select
“Add Angular Routing” during project creation, make sure you have this in
app.module.ts:
app.module.ts
import {
RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes
= [
{ path: 'home', component:
HomeComponent },
{ path: 'about', component:
AboutComponent },
{ path: '', redirectTo: 'home',
pathMatch: 'full' }, // default route
{ path: '**', redirectTo: 'home' }, //
wildcard (404)
];
@NgModule({
declarations: [AppComponent,
HomeComponent, AboutComponent],
imports: [BrowserModule,
RouterModule.forRoot(routes)],
bootstrap: [AppComponent]
})
export class AppModule {}
✅
2. Add <router-outlet> in Your Template
This is where Angular
will render the routed components.
app.component.html
<nav>
<a routerLink="/home"
routerLinkActive="active">Home</a>
<a routerLink="/about"
routerLinkActive="active">About</a>
</nav>
<router-outlet></router-outlet>
✅
3. Use routerLink to Navigate
In templates:
<a
routerLink="/about">Go to About</a>
In code (e.g., a
button click):
import { Router }
from '@angular/router';
constructor(private
router: Router) {}
goToAbout() {
this.router.navigate(['/about']);
}
🚀 Advanced Routing Features
🔀 Route Parameters
{ path: 'user/:id',
component: UserComponent }
In component:
constructor(private
route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params
=> {
console.log(params['id']);
});
}
🔒 Route Guards
Protect routes from
unauthorized access:
{ path: 'admin',
component: AdminComponent, canActivate: [AuthGuard] }
📦 Lazy Loading Modules
{ path: 'dashboard',
loadChildren: () => import('./dashboard/dashboard.module').then(m =>
m.DashboardModule) }
🧠 Summary
Feature |
Purpose |
RouterModule |
Enables
routing |
routerLink |
Template
navigation |
router-outlet |
Displays
the current route’s component |
navigate() |
Navigate
in TypeScript |
ActivatedRoute |
Access
route params |
Route
Guards |
Protect
or control access |
No comments:
Post a Comment