Mastering Navigation: The Angular Router
In traditional web development, navigating to a new page meant requesting a completely new HTML file from the server. This is slow and resets the application state. Angular, being a Single Page Application (SPA) framework, takes a different approach. It uses the Router to map browser URLs to views (components) instantly, without a full page reload.
The Core Trifecta: Config, Outlet, and Links
To make routing work, you need three main pieces moving in harmony:
- Route Configuration: An array of objects defining the `path` and the `component` to load.
- Router Outlet: The
<router-outlet>directive marks the spot in your HTML where the active component will be displayed. - Router Link: The
routerLinkdirective allows users to click and navigate, handling the URL update internally.
Dynamic Navigation with Parameters
Static pages are rarely enough. You often need to display details for a specific item, like a user profile or a product. This is where Route Parameters come in.
Definition
{ path: 'products/:id', component: ProductDetailComponent }The colon : tells Angular that `id` is a placeholder for dynamic data.
Usage
<a [routerLink]="['/products', 123]">View Product</a>We pass an array to `routerLink`. The router constructs the URL /products/123.
Inside your component, you can then use the ActivatedRoute service to read this ID and fetch the correct data.
Pro Tip: Always place your Wildcard route { path: '**', ... } at the very bottom of your Routes array. Since Angular matches routes from top to bottom, putting it earlier will cause it to "swallow" valid routes that come after it.