Routing & Navigation
Angular Router maps URL paths to component views, enabling multi-page navigation in single-page applications without full page reloads.
1 Routing Parameters and Routes Mapping
Configuring routing requires setting up path routes mappings:
- path: The URL path matched by the browser (e.g.
'users'matches/users). - component: The view component template to render when the path is matched.
- router-outlet: A placeholder tag telling the router where to render the matched component.
- routerLink: Directive attribute used on anchors to navigate without refreshing:
routerLink="/users".
2 Defining routes configurations
Let's check a standard routing configuration:
TypeScript — App Routing setup
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { UserDetailComponent } from './user-detail.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'user/:id', component: UserDetailComponent }, // dynamic route parameter
{ path: '**', redirectTo: '' } // wildcard redirect
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
Access dynamic route parameters (like :id) inside components using the ActivatedRoute service:
TypeScript — Route parameters access
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-user-detail',
template: `Viewing profile ID: {{ userId }}
`
})
export class UserDetailComponent implements OnInit {
userId: string | null = null;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Read route param parameter mapping
this.userId = this.route.snapshot.paramMap.get('id');
}
}
3 Code Challenge
Challenge: Add a navigation links bar with
routerLinkActive="active" attributes on the anchors. Verify the active CSS class is applied when navigating to the corresponding route.