What is the Angular Router?
The Angular Router is a powerful library that enables navigation from one view to the next as users perform tasks. It interprets browser URLs as instructions to change the view. Instead of the browser requesting a new page from the server, the Router swaps out components within the current page, maintaining the 'Single Page' experience.
- Defining Your Route Configuration
Routes are defined as an array of objects. Each route typically has a path (the URL segment) and a component (the view to display). As an architect, you should define a 'Wildcard' route at the end to handle 404 - Not Found scenarios.
- The Router-Outlet and RouterLink
To display the routed components, you must place the <router-outlet> directive in your main HTML. This acts as a placeholder where the Router will 'plug in' the component for the current route. To navigate, use the routerLink directive instead of standard href to avoid full page reloads.
Navigation Lifecycle
Understanding the navigation lifecycle is key for debugging. The Router follows a strict sequence: it recognizes the URL, applies redirects, runs guards (security), resolves data, and finally activates the component.
- Accessing Route Parameters
For dynamic routes like /project/:id, the component needs to know which ID was passed. You use the ActivatedRoute service to subscribe to these parameters. This is essential for a Lead Developer building data-driven dashboards.
Routing Features Summary
| Feature | Syntax/Directive | Purpose |
|---|---|---|
| Navigation Placeholder | <router-outlet> | Where the routed view appears |
| Nav Link | routerLink | User-facing links (prevents reload) |
| Active State | routerLinkActive | CSS class for the current route |
| Dynamic Params | :id | Passing variables through the URL |
| Redirect | redirectTo | Sending users from one path to another |