Skip to content

Routing

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>.

app.routes.ts
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.ts
bootstrapApplication(AppComponent, {
providers: [provideRouter(routes)],
});
app.component.html
<nav>
<a routerLink="/">Home</a>
<a routerLink="/users">Users</a>
</nav>
<router-outlet></router-outlet>
// Reading a route parameter and navigating programmatically
export class UserDetailComponent {
private route = inject(ActivatedRoute);
private router = inject(Router);
userId = this.route.snapshot.paramMap.get('id');
goBack() {
this.router.navigate(['/users']);
}
}

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 last
export const routes: Routes = [
{ path: 'users', component: UserListComponent },
{ path: '**', component: NotFoundComponent },
];
  1. What does :id mean in a route path like 'users/:id'?

    AnswerA route parameter β€” a dynamic segment of the URL, readable in the target component via ActivatedRoute.
  2. Why must the wildcard route (path: '**') always be the last entry in the routes array?

    AnswerThe 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.
  3. What does loadComponent: () => import(...) enable?

    AnswerLazy loading β€” that route's component (and its dependencies) is only downloaded when the user actually navigates to it, reducing the initial bundle size.