Sub topic 2
Defining Routes and Registering the Router
This chapter covers the two things every Angular routing setup needs. The first is a route table, which says which URL shows which component. The second is the router itself, which you register with provideRouter when the application starts up. If either one is missing or set up wrong, nothing else in routing works. Navigation fails quietly, links do nothing, or you get dependency injection errors.
The chapter assumes you already know TypeScript, Angular components and templates, standalone components, inject(), and how services are provided through dependency injection. You don't need any routing knowledge yet.
The Routes Array
A route table is an array of Route objects with the type Routes. Each object describes one URL pattern and what to do when the URL matches it. The router reads the array when the app starts and checks it again on every navigation.
Here is a minimal but complete configuration:
// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { ProductListComponent } from './product-list.component';
import { ProductDetailComponent } from './product-detail.component';
import { NotFoundComponent } from './not-found.component';
export const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent, title: 'Home' },
{ path: 'products', component: ProductListComponent, title: 'Products' },
{ path: 'products/:id', component: ProductDetailComponent, title: 'Product details' },
{ path: '**', component: NotFoundComponent, title: 'Not found' }
];Keeping the table in its own file (app.routes.ts) is the convention the Angular CLI generates. It keeps the configuration easy to find, and you can import it into tests.
The Properties You Will Use Most
| Property | Purpose | Example |
|---|---|---|
| `path` | URL pattern relative to the parent route, without a leading slash | `'products/:id'` |
| `component` | Component rendered when the route matches | `HomeComponent` |
| `title` | Text set as `document.title` after navigation | `'Home'` |
| `redirectTo` | Target URL to redirect to instead of rendering | `'home'` |
| `pathMatch` | `'prefix'` (default) or `'full'`; controls how much of the URL must match | `'full'` |
| `data` | Static, read-only values attached to the route | `{ section: 'shop' }` |
| `children` | Nested routes rendered inside this route's component | `[...]` |
| `loadComponent` / `loadChildren` | Lazy-loaded component or route group | `() => import(...)` |
| `canActivate`, `canMatch`, `resolve` | Guards and resolvers | `[authGuard]` |
Later chapters cover children, lazy loading, guards, resolvers, and the details of redirects and wildcards. This chapter is about path, component, title, data, and how the table as a whole gets matched.
Path Syntax
A path is made of segments separated by /. Each segment is one of three kinds:
- A static segment such as
products. It matches only that exact text. - A parameter segment such as
:id. It matches any single segment and captures its value under the nameid. - The wildcard
**. It matches any URL, whatever is left of it.
The empty path '' matches an empty URL segment. It is the usual way to define the default route.
Paths are always relative. You write 'products/:id', never '/products/:id'. A leading slash makes the router throw an error when it validates the configuration at startup.
How the Router Matches a URL
The router does not look for the best match. It walks the array in order and uses the first route that matches. Inside nested configurations it searches depth-first, but the rule at each level is still first match wins.
Order has two practical effects:
- Specific routes go before general ones. If
'**'comes first, it matches everything and none of the routes after it are ever reached. The same thing happens if you place':slug'above'about'at the same level:aboutgets captured as a slug. - A leaf route must use up the whole URL.
'products'does not match/products/7for a component route with no children, because the segment7would be left over. The router backtracks and tries the next route. This is whyproductsandproducts/:idcan sit side by side without conflict.
Registering the Router with provideRouter
A route table does nothing until you hand it to the router. In a standalone application you do this with provideRouter, passed in the providers when the app bootstraps. The CLI's pattern puts the providers in app.config.ts:
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import {
provideRouter,
withComponentInputBinding,
withInMemoryScrolling
} from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(
routes,
withComponentInputBinding(),
withInMemoryScrolling({ scrollPositionRestoration: 'enabled' })
)
]
};// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { appConfig } from './app.config';
bootstrapApplication(AppComponent, appConfig).catch(err => console.error(err));provideRouter registers the Router service, ActivatedRoute, the location services, and the initial navigation that runs at startup. Call it once, at the root. Feature areas add their own routes through children or loadChildren. They do not call provideRouter again.
Router Features
The second and later arguments to provideRouter are feature functions. Each one turns on optional behavior. Because each feature is a separate function, the bundler can drop the ones you don't import.
| Feature | Effect |
|---|---|
| `withComponentInputBinding()` | Binds route params, query params, `data`, and resolved data to component `@Input()`s with matching names |
| `withInMemoryScrolling({...})` | Restores scroll position on back/forward and scrolls to anchors |
| `withDebugTracing()` | Logs every router event to the console (development only) |
| `withHashLocation()` | Uses `#/path` URLs instead of HTML5 paths |
| `withPreloading(PreloadAllModules)` | Downloads lazy routes in the background after startup |
| `withRouterConfig({...})` | Fine-tunes behavior such as `onSameUrlNavigation` and `paramsInheritanceStrategy` |
| `withViewTransitions()` | Animates route changes with the browser View Transitions API |
withDebugTracing() is very useful while you learn. Turn it on for an afternoon and watch how a navigation moves through recognition, guards, resolvers, and activation.
Titles and Static Data
The title property sets the browser tab text after each successful navigation. That improves browser history entries and screen reader announcements without any code in your components. title can also be a resolver function when the title depends on loaded data.
The data property attaches static values that the router never changes. It is a good place for breadcrumb labels, analytics tags, or layout flags:
import { Routes } from '@angular/router';
import { ReportsComponent } from './reports.component';
export const reportRoutes: Routes = [
{
path: 'reports',
component: ReportsComponent,
title: 'Reports',
data: { breadcrumb: 'Reports', fullWidth: true }
}
];With withComponentInputBinding() turned on, ReportsComponent can declare @Input() fullWidth = false; and receive true from the route data. Without that feature, you read the value from inject(ActivatedRoute).snapshot.data.
Common Errors and What They Mean
| Symptom | Likely cause | Fix |
|---|---|---|
| `NullInjectorError: No provider for ActivatedRoute` (or `Router`) | `provideRouter` missing from the bootstrap providers, or a test that doesn't provide it | Add `provideRouter(routes)` to `appConfig` or the test's providers |
| Error at startup that a path cannot start with a slash | `path: '/home'` | Remove the leading slash |
| Every URL shows the not-found page | `'**'` route placed before other routes | Move the wildcard to the end of the array |
| Every URL redirects to the same place, or the browser hangs | Empty-path redirect without `pathMatch: 'full'` | Add `pathMatch: 'full'` |
| Error saying `redirectTo` and `component` cannot be used together | Both set on one route | Use one or the other |
| URL changes but nothing renders | No `<router-outlet>` in the template (next chapter) | Add `RouterOutlet` to the component's template and imports |
| `@Input()` from the URL stays `undefined` | `withComponentInputBinding()` not enabled, or input name differs from the param name | Enable the feature and match the names exactly |
The router checks the route table for structural errors during startup. Configuration mistakes like these show up as soon as the app boots, so read the console before you start debugging templates.
Exercise
A team's route table is [{ path: '**', component: NotFoundComponent }, { path: 'home', component: HomeComponent }, { path: '', redirectTo: 'home' }]. Users always see the not-found page, even at the root URL. Name every problem and give the corrected array.
Show answer
First, the wildcard is listed first, and because the router uses the first match, it captures every URL. Second, the empty-path redirect has no pathMatch: 'full', so once it can be reached it would match every URL as a prefix. The corrected array is [{ path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: '**', component: NotFoundComponent }].
Exercise
Your table contains { path: 'products', component: ProductListComponent } followed by { path: 'products/:id', component: ProductDetailComponent }. Does the URL /products/9 render the list or the detail page, and why?
Show answer
It renders the detail page. A component route with no children has to use up the entire URL. 'products' would leave the segment 9 unmatched, so the router backtracks and tries the next route. 'products/:id' matches both segments and captures id = '9'.
Exercise
You enable withComponentInputBinding() and add data: { theme: 'dark' } to a route. What must the routed component declare to receive the value, and what would you use instead without that feature?
Show answer
The component declares an input with the same name, such as @Input() theme?: string;. Without the feature, it injects ActivatedRoute and reads route.snapshot.data['theme'], or subscribes to route.data.