Routing
Routing
Section titled βRoutingβWhat it means
Section titled βWhat it meansβAngularβs Router maps URL paths to components, enabling single-page-app navigation without full page reloads. Routes are configured as an array of path-to-component mappings, provided to the app via provideRouter() (modern standalone apps) or RouterModule.forRoot() (NgModule-based apps), and rendered into the page via <router-outlet>.
Examples
Section titled βExamplesβexport const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'users', component: UserListComponent }, { path: 'users/:id', component: UserDetailComponent }, // :id is a route parameter { path: 'admin', loadComponent: () => import('./admin.component').then(m => m.AdminComponent) }, // lazy-loaded { path: '**', component: NotFoundComponent }, // wildcard, catches unmatched routes];
// app.config.tsbootstrapApplication(AppComponent, { providers: [provideRouter(routes)],});<nav> <a routerLink="/">Home</a> <a routerLink="/users">Users</a></nav><router-outlet></router-outlet>// Reading a route parameter and navigating programmaticallyexport class UserDetailComponent { private route = inject(ActivatedRoute); private router = inject(Router);
userId = this.route.snapshot.paramMap.get('id');
goBack() { this.router.navigate(['/users']); }}Common mistake
Section titled βCommon mistakeβPutting the wildcard route (path: '**') anywhere but last in the routes array β the router checks routes in order and stops at the first match, so a wildcard placed earlier swallows every route defined after it.
export const routes: Routes = [ { path: '**', component: NotFoundComponent }, // matches EVERYTHING, including routes below! { path: 'users', component: UserListComponent }, // never reached];
// Fix: wildcard must always be lastexport const routes: Routes = [ { path: 'users', component: UserListComponent }, { path: '**', component: NotFoundComponent },];Quick practice
Section titled βQuick practiceβ-
What does
:idmean in a route path like'users/:id'?Answer
A route parameter β a dynamic segment of the URL, readable in the target component viaActivatedRoute. -
Why must the wildcard route (
path: '**') always be the last entry in the routes array?Answer
The router matches routes in order and stops at the first match; since a wildcard matches any path, placing it earlier would prevent every route listed after it from ever being reached. -
What does
loadComponent: () => import(...)enable?Answer
Lazy loading β that route's component (and its dependencies) is only downloaded when the user actually navigates to it, reducing the initial bundle size.