Routing
Router
Master Angular Router fundamentals, covering route configuration, RouterModule setup, navigation links, route parameters, and child routes.
1. Learning Objectives
In this lesson, you will master the Angular Router. By the end of this topic, you will be able to:
- Configure routes using the
Routesarray andprovideRouter(). - Navigate between views using
routerLinkand theRouterservice. - Extract route parameters using
ActivatedRoute. - Organize complex layouts using child routes and nested
<router-outlet>elements. - Handle unknown paths with wildcard routes and redirect configurations.
2. Overview
The Angular Router is a standalone module that maps URL paths to component views. It enables single-page application (SPA) navigation without full page reloads. Routes are defined as a flat or nested array of path-to-component mappings, and Angular renders the matched component inside a <router-outlet> placeholder element.
3. Why This Topic Matters
Routing is the backbone of Angular navigation:
- Single-Page Application Navigation: Without routing, navigating between different screens would require full browser page reloads, losing all component state and user context. The Angular Router swaps component views in-place, preserving the application shell.
- Route Order Errors: Angular evaluates routes in the order they are defined. Placing a wildcard route (
**) before specific routes will match everything and prevent the specific routes from ever being reached.
4. Real-World Analogy
Think of the Angular Router like **a building elevator system**:
- The Elevator Panel (Routes Array): The panel lists all floors (paths). Each button maps to a specific floor (component).
- The Elevator Shaft (router-outlet): The physical space where floor content is displayed. When you press a button, the elevator door opens to reveal the matching floor.
- Floor Numbers (Route Parameters): Some floors have room numbers (like
/rooms/:id). The elevator knows which specific room to open based on the parameter value in the URL. - Sub-Floors (Child Routes): Some floors have internal wings. The main elevator takes you to the floor, and a smaller internal elevator (nested router-outlet) navigates between wings.
5. Core Concepts
The Angular Router uses several key building blocks:
- Routes: An array of route definition objects, each mapping a
pathstring to acomponentclass. - RouterOutlet: A directive (
<router-outlet>) that acts as a placeholder where matched components are rendered. - RouterLink: A directive applied to anchor tags to enable SPA-style navigation without full page reloads.
- ActivatedRoute: An injectable service that provides access to the current route's parameters, query parameters, and data.
| Route Property | Type | Purpose |
|---|---|---|
| path | string | The URL segment to match (e.g. 'products' or 'products/:id'). |
| component | Type | The component class to render when the path matches. |
| redirectTo | string | Redirects navigation to a different path (requires pathMatch). |
| children | Routes[] | An array of child route definitions rendered inside a nested <router-outlet>. |
| pathMatch | 'full' | 'prefix' | Determines how the router matches the path. 'full' requires an exact match. |
6. Syntax & API Reference
Below is a standalone application bootstrapped with provideRouter() and a routes configuration array:
7. Visual Diagram
This diagram displays how the Router matches URL paths to component views:
8. Live Example — Full Working Code
Below is a component that reads route parameters using ActivatedRoute and navigates programmatically using the Router service:
Child Routes Example
Below is a parent route with nested child routes and a secondary <router-outlet>:
9. Interactive Playground
Try It Yourself Challenges:
- Add a new route that maps
/settingsto a SettingsComponent. - Move the wildcard route above the
/homeroute and observe what happens.
10. Common Mistakes
| Mistake | Why it happens | Wrong | Correct |
|---|---|---|---|
| Placing wildcard route before specific routes | The router evaluates routes in array order. A wildcard (**) placed early matches all paths, preventing subsequent routes from ever being reached. |
[{ path: '**', ... }, { path: 'home', ... }] |
[{ path: 'home', ... }, { path: '**', ... }] |
| Missing pathMatch on redirect routes | Redirect routes with an empty path require pathMatch: 'full', otherwise every URL that starts with an empty prefix will be redirected. |
{ path: '', redirectTo: 'home' } |
{ path: '', redirectTo: 'home', pathMatch: 'full' } |
11. Best Practices
- Define routes in a separate file: Keep route definitions in a dedicated
app.routes.tsfile rather than inline in the main application bootstrap. - Place wildcard routes last: Always define the catch-all wildcard route (
**) as the last entry in the routes array. - Use routerLinkActive for active states: Apply the
routerLinkActivedirective to navigation links to automatically add CSS classes when the route is active. - Unsubscribe from paramMap observables: When subscribing to
paramMapinsidengOnInit, store the subscription and unsubscribe inngOnDestroyto prevent memory leaks.
12. Browser Compatibility/Requirements
The Angular Router uses the History API (pushState) by default, which is supported in all modern browsers. For legacy browser support, Angular provides a HashLocationStrategy fallback that uses URL hash fragments instead.
13. Interview Questions
Q1: What is the purpose of the router-outlet directive in Angular?
Answer: The <router-outlet> directive is a placeholder element in the template where the Angular Router renders the component that matches the current URL path. When the URL changes, the Router swaps the component displayed inside the outlet without reloading the entire page.
Q2: Explain the difference between pathMatch 'full' and 'prefix'.
Answer: With pathMatch: 'full', the router only matches if the entire remaining URL segment matches the route's path exactly. With pathMatch: 'prefix' (the default), the router matches if the URL starts with the route's path. The 'full' strategy is required for empty-path redirect routes to prevent infinite redirects.
14. Debugging Exercise
Identify and fix the routing configuration error:
Diagnosis:
1. The wildcard route (**) is placed first. Since routes are evaluated in order, the wildcard matches every URL, so /home and /about are never reached.
2. The empty-path redirect is missing pathMatch: 'full', which would cause every URL to match the empty prefix and trigger an infinite redirect loop.
Fixed routes configuration:
15. Practice Exercises
Exercise 1: Build a multi-page SPA
Create a standalone Angular app with Home, About, and Contact pages. Add a navigation bar with routerLink directives and highlight the active link using routerLinkActive. Include a 404 wildcard fallback page.
16. Scenario-Based Challenge
The Admin Panel Layout Challenge:
You must build an admin panel with a persistent sidebar and header. The sidebar contains links to Dashboard, Users, and Settings pages. Each page loads inside a nested router-outlet within the admin layout shell. The default route should redirect to the Dashboard view.
17. Quick Quiz
Q1: Where should the wildcard route (**) be placed in the Routes array?
A) At the beginning of the array
B) Anywhere in the array
C) At the end of the array
Answer: C — The wildcard route must be placed at the end, because routes are evaluated in order and the wildcard matches every URL.
18. Summary & Key Takeaways
- The Angular Router maps URL path segments to component views rendered inside router-outlet placeholders.
- Routes are evaluated in array order, so always place wildcard routes last.
- Use ActivatedRoute to access route parameters and the Router service for programmatic navigation.
- Child routes enable nested layouts with multiple router-outlet levels.
19. Cheat Sheet
| API | Purpose |
|---|---|
provideRouter(routes) |
Registers routes at application bootstrap for standalone apps. |
routerLink |
Directive for SPA navigation on anchor tags. |
router.navigate() |
Programmatic navigation via the Router service. |
route.paramMap |
Observable of route parameter values via ActivatedRoute. |