Sub topic 6
Reading Route Parameters
A route parameter is a variable segment in a URL path, such as the 42 in /products/42. You declare it in the route definition with a colon prefix (products/:id), and the router pulls the matching value out of the URL when navigation succeeds. This chapter covers three ways to read that value: the ActivatedRoute snapshot, the ActivatedRoute observables, and component input binding. It also covers the bugs each approach tends to cause.
This chapter assumes you already know TypeScript, standalone components, inject(), basic RxJS operators such as map and switchMap, and the route configuration and RouterLink material from earlier chapters.
How a Parameter Travels from URL to Component
When the router matches /products/42 against { path: 'products/:id', ... }, it builds an ActivatedRoute object for that route. ActivatedRoute holds the matched parameters, the query parameters, the route data, and links to parent and child routes. The router then creates the component, or reuses it, and makes this information available to it.
Every parameter value is a string. The URL is text, and the router does not convert types. If your service expects a number, you have to convert the value yourself.
Approach 1: The Snapshot
The simplest way to read a parameter is to take the snapshot when the component is created:
import { Component, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product-detail',
standalone: true,
template: `<h2>Product {{ id }}</h2>`
})
export class ProductDetailComponent {
private route = inject(ActivatedRoute);
id = this.route.snapshot.paramMap.get('id');
}paramMap is a ParamMap, a read-only map interface with get(name), getAll(name), has(name), and keys. get returns string | null, so TypeScript makes you deal with a parameter that might be missing. There is also an older params property, a plain object (snapshot.params['id']), which still works. paramMap is preferred because its API is explicit about missing keys.
The component reuse trap
The snapshot is a picture of the route at one moment in time. That leads to the most common route parameter bug in Angular.
When you navigate from /products/42 to /products/43, both URLs match the same route configuration. By default the router reuses the existing component instance instead of destroying it and creating a new one. The constructor and field initializers do not run again, so id stays '42' while the URL shows 43.
This happens whenever a page links to another instance of the same route: "related products" lists, next/previous buttons, or a sidebar of items next to a detail view. If users can never navigate from one parameter value to another without first leaving the route, the snapshot is safe. Otherwise, use one of the reactive approaches below.
Approach 2: The paramMap Observable
ActivatedRoute.paramMap (without snapshot) is an Observable<ParamMap>. It emits the current parameters as soon as you subscribe, and emits again every time they change on a reused component. Use switchMap to turn each id into a data request. switchMap also cancels any request still in flight when a new id arrives:
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { map, switchMap } from 'rxjs';
import { ProductService } from './product.service';
@Component({
selector: 'app-product-detail',
standalone: true,
imports: [AsyncPipe],
template: `
@if (product$ | async; as product) {
<h2>{{ product.name }}</h2>
} @else {
<p>Loading…</p>
}
`
})
export class ProductDetailComponent {
private route = inject(ActivatedRoute);
private products = inject(ProductService);
product$ = this.route.paramMap.pipe(
map(params => params.get('id')!),
switchMap(id => this.products.getProduct(id))
);
}You do not need to unsubscribe manually from ActivatedRoute observables. The router completes them when the route is destroyed, and the async pipe handles the template subscription.
If you work with signals, toSignal from @angular/core/rxjs-interop turns the stream into a signal: id = toSignal(this.route.paramMap.pipe(map(p => p.get('id')))). Call it in an injection context, such as a field initializer.
Approach 3: Component Input Binding
If the router is registered with provideRouter(routes, withComponentInputBinding()), as in the earlier configuration chapter, it writes route parameters directly into component inputs with matching names. Query parameters, static route data, and resolved data are bound the same way. The component no longer needs to know about ActivatedRoute:
import { Component, computed, input } from '@angular/core';
@Component({
selector: 'app-product-detail',
standalone: true,
template: `<h2>Product {{ productId() }}</h2>`
})
export class ProductDetailComponent {
// Bound from the :id segment of 'products/:id'
id = input.required<string>();
productId = computed(() => Number(this.id()));
}Decorator inputs work too (@Input() id!: string;), and you can use a setter if you need to react to each change. Unlike the snapshot, bound inputs are updated when a reused component receives new parameters, so the reuse trap does not apply here. Components written this way are also easier to test: you set the input and skip mocking ActivatedRoute.
Input binding gotchas
- The names must match. The
:idparameter binds only to an input namedid. If you want a different property name, alias it:productId = input.required<string>({ alias: 'id' }). - Missing keys become
undefined. When a navigation drops a value that used to be bound, for example a query parameter that is no longer in the URL, the router sets the input toundefined. Arequiredinput typed asstringcan then holdundefinedat runtime for keys that are not always present. Declare optional keys asinput<string | undefined>(). - Name collisions. If a path parameter, a query parameter, and a
datakey share a name, only one value reaches the input. Use distinct names. - Only routed components. Binding applies to the component the router renders in an outlet, not to that component's children. Pass values down to children with ordinary inputs.
Multiple and Parent Parameters
A route can declare several parameters: { path: 'stores/:storeId/products/:productId', component: ... }. Each one appears in paramMap and binds to its own input.
Nested routes behave differently. Given this configuration:
import { Routes } from '@angular/router';
import { StoreComponent } from './store.component';
import { StoreProductComponent } from './store-product.component';
export const routes: Routes = [
{
path: 'stores/:storeId',
component: StoreComponent,
children: [
{ path: 'products/:productId', component: StoreProductComponent }
]
}
];the child's ActivatedRoute contains only productId. Parameters are scoped to the route that declares them. You can reach the parent's value with route.parent?.paramMap, but that ties the child to the shape of the route tree. The alternative is to have the router merge parent parameters into child routes:
import { provideRouter, withComponentInputBinding, withRouterConfig } from '@angular/router';
import { routes } from './app.routes';
export const appProviders = [
provideRouter(
routes,
withComponentInputBinding(),
withRouterConfig({ paramsInheritanceStrategy: 'always' })
)
];With 'always', StoreProductComponent can declare both storeId and productId inputs. The cost is that the setting applies to the whole application, which raises the chance of the name collisions described above. Child routes get their own chapter later in this tutorial.
Choosing an Approach
| Approach | Updates on reuse | Needs ActivatedRoute | Best for |
|---|---|---|---|
| `snapshot.paramMap` | No | Yes | Components the user always leaves before the parameter changes |
| `paramMap` observable | Yes | Yes | RxJS pipelines that chain parameters into HTTP calls |
| Input binding | Yes | No | New code; simple, testable components |
For new standalone applications, use input binding by default, and add a switchMap pipeline (or toObservable on the input signal) when you need request cancellation. Use the observable directly in code bases that do not enable withComponentInputBinding. Use the snapshot only when you know the component cannot be reused for a different parameter value.
Common Errors
- Treating the value as a number.
params.get('id') === 42is always false. Convert the value withNumber()and check forNaN, because/products/abcmatchesproducts/:idtoo. - Forgetting the non-null case. The
!inparams.get('id')!is safe only when the route path guarantees the segment. In shared components, handlenull. - Reading inputs in the constructor. Bound inputs are not set yet during construction. Read them in
ngOnInit, in acomputed, or in the template. - Expecting parent parameters in a child without
paramsInheritanceStrategy: 'always'orroute.parent.
Exercise
A ProductDetailComponent reads its id with this.route.snapshot.paramMap.get('id') in a field initializer. Its template has a "Next product" link to /products/43 while the user is viewing /products/42. After the click, the URL changes but the heading still says "Product 42". Explain why, and give two fixes.
Show answer
Both URLs match the same products/:id route, so the router reuses the existing component instance. The field initializer ran once, and the snapshot does not update. Fix 1: subscribe to this.route.paramMap (for example paramMap.pipe(map(p => p.get('id'))) with the async pipe or toSignal). Fix 2: enable withComponentInputBinding() and declare id = input.required<string>(), which the router updates on every parameter change.
Exercise
With withComponentInputBinding() enabled, a component on the route orders/:orderId declares id = input<string>(). The value is always undefined. What is wrong, and how do you fix it without renaming the route parameter?
Show answer
Input binding matches by name, and no route key is called id. Add an alias so the input binds to the existing parameter: id = input<string>(undefined, { alias: 'orderId' }), or input.required<string>({ alias: 'orderId' }).
Exercise
A child route products/:productId is nested under stores/:storeId. The child component needs both values as inputs. What router configuration makes that possible, and what risk does it introduce?
Show answer
Register the router with withRouterConfig({ paramsInheritanceStrategy: 'always' }) alongside withComponentInputBinding(), so child routes inherit parent parameters. The setting is global. Parent and child keys with the same name can then collide, and every route receives more inherited values than before.