Angular Routing & Navigation
Angular's router enables navigation from one view to the next as users perform application tasks. It allows you to build single-page applications with multiple views and navigate between them.
Router Basics
The Angular Router is an optional service that presents a particular component view for a given URL. It provides:
- Navigation between views in response to user actions
- Passing optional parameters to routed components
- Lazy loading of feature modules
- Guarding against unauthorized access
Setting Up Routing
First, import the RouterModule and Routes in your app module:
// app.module.ts
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'products', component: ProductsComponent },
{ path: 'products/:id', component: ProductDetailComponent },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppModule { }
Router Outlet
Add the router outlet directive to your app component template:
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
Navigation
You can navigate in two ways:
- Using routerLink directive in templates
- Using Router service in components
Template Navigation
<!-- Basic navigation -->
<a routerLink="/products">Products</a>
<!-- Navigation with parameter -->
<a [routerLink]="['/products', product.id]">{{product.name}}</a>
<!-- Navigation with query params -->
<a [routerLink]="['/products']" [queryParams]="{filter: 'active'}">Active Products</a>
Programmatic Navigation
// In your component
import { Router } from '@angular/router';
constructor(private router: Router) {}
navigateToProducts() {
this.router.navigate(['/products']);
}
navigateToProductDetail(id: number) {
this.router.navigate(['/products', id]);
}
navigateWithQueryParams() {
this.router.navigate(['/products'], {
queryParams: { filter: 'active' }
});
}
Route Parameters
To access route parameters in your component:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Get route parameter
this.route.params.subscribe(params => {
this.productId = params['id'];
});
// Get query parameter
this.route.queryParams.subscribe(params => {
this.filter = params['filter'];
});
}
Route Guards
Guards control whether a route can be activated or deactivated:
// auth.guard.ts
import { CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService) {}
canActivate() {
return this.authService.isLoggedIn();
}
}
// Apply to route
{
path: 'admin',
component: AdminComponent,
canActivate: [AuthGuard]
}
Lazy Loading
Load feature modules only when needed:
const routes: Routes = [
{
path: 'customers',
loadChildren: () => import('./customers/customers.module')
.then(m => m.CustomersModule)
}
];
Router Events
You can listen to router events for navigation tracking:
this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
// Navigation started
}
if (event instanceof NavigationEnd) {
// Navigation completed
}
});
Next: Reactive Forms