Jali's menu has three pancakes, and each one needs its own detail page. If you write one route per pancake, the route list grows every time a new item joins the menu.
A route parameter solves this problem. A route parameter is the part of an address whose content can change. /menu/1, /menu/2 and /menu/3 are served by one route, menu/:id, and one component. That component then reads the number in its address. Picture the pickup counter at Jali's Pancake Stall. There's only one counter, but the number on your ticket decides which pancake you get. The menu/:id route is the counter, the number in the address is the ticket number, and ?portions=2 is an extra note on the same ticket.
A route with :id
This is the route list, with one new route, menu/:id:
// src/app/app.routes.ts
export const routes: Routes = [
{ path: '', redirectTo: 'menu', pathMatch: 'full' },
{ path: 'menu', component: MenuPage },
{ path: 'menu/:id', component: MenuDetail },
{ path: '**', component: NotFound },
]
In MenuPage's template, @for makes two links for each pancake m in the menu list: a link to its detail page, and the same link for 2 portions.
<!-- MenuPage's template, with RouterLink in imports -->
@for (m of menu; track m.id) {
<p>
<a [routerLink]="['/menu', m.id]">{{ m.name }}</a>
<a [routerLink]="['/menu', m.id]" [queryParams]="{ portions: 2 }">2 portions</a>
</p>
}
The paramMap.get('id') column of this table is explained in the next section.
| Address | Matching route | paramMap.get('id') |
|---|---|---|
/menu |
menu (MenuPage) |
none |
/menu/2 |
menu/:id (MenuDetail) |
'2' |
/menu/2?portions=2 |
menu/:id (MenuDetail) |
'2' |
- The colon in
:idmakes that part of the address a parameter: whatever is written there is accepted, and its name isid. [routerLink]="['/menu', m.id]"builds the address from pieces:'/menu', then the pancake's id. The Special Egg Pancake has the id 2, so its link goes to/menu/2.[queryParams]="{ portions: 2 }"adds?portions=2to the end of the address. The part after?is called a query parameter: an extra note in the address. Query parameters are not written in the route list.
Reading the id: ActivatedRoute
ActivatedRoute is a service from @angular/router that holds details about the route currently showing this component: its parameters, its query parameters and its address. In the MenuDetail component below, MENU is the list of pancakes from the file menu-data, and Menu is the type for one pancake.
import { Component, OnInit, inject } from '@angular/core'
import { ActivatedRoute, RouterLink } from '@angular/router'
import { MENU, Menu } from '../menu-data'
@Component({
selector: 'app-menu-detail',
standalone: true,
imports: [RouterLink],
template: `
<h2>{{ menu?.name ?? 'Menu not found' }}</h2>
<p>{{ portions }} portions, total {{ '$' + (menu?.price ?? 0) * portions }}</p>
<p>See also:
@for (m of others; track m.id) {
<a [routerLink]="['/menu', m.id]">{{ m.name }}</a>
}
</p>
`,
})
export class MenuDetail implements OnInit {
private route = inject(ActivatedRoute)
menu?: Menu
portions = 1
get others() {
return MENU.filter((m) => m.id !== this.menu?.id)
}
ngOnInit() {
const id = this.route.snapshot.paramMap.get('id') // '2', text
this.menu = MENU.find((m) => m.id === Number(id))
this.portions = Number(this.route.snapshot.queryParamMap.get('portions') ?? 1)
}
}
inject(ActivatedRoute)asks for the service, just likeinject(CartService)in the Services and DI lesson.snapshotis the route's state at the moment you read it.paramMapholds the route's parameters, and.get('id')takes one parameter by its name.snapshot.paramMap.get('id')gives'2'for/menu/2, ornullwhen the route has no parameter namedid.- When it's there, the value is always text. The ids in
MENUare numbers, so convert it withNumber(id)before comparing. - Angular calls
ngOnInitonce, after the component is created. The details are in the Lifecycle Hooks lesson. - In the template,
menu?.name ?? 'Menu not found'shows the pancake's name, orMenu not foundwhenmenuis empty (the id from the address isn't inMENU). - The older form,
this.route.params, gives a plain object:this.route.params.subscribe((p) => (this.id = p['id'])).
snapshot or paramMap
Before you read on, guess. You're on /menu/1, the Chocolate Cheese Pancake page, and you click the "See also: Special Egg Pancake" link. The address becomes /menu/2. Does the page's heading change too?
The heading does not change. The router reuses the same component when only the parameter changes. From /menu/1 to /menu/2, MenuDetail is not created again, so ngOnInit doesn't run again:
| Step | Address | MenuDetail instance | Read in ngOnInit |
What shows |
|---|---|---|---|---|
| Open from Menu | /menu/1 |
#1 created | '1' |
Chocolate Cheese Pancake |
| Click "See also: Special Egg Pancake" | /menu/2 |
#1 reused | not read again | Chocolate Cheese Pancake |
| Back to Menu, open it again | /menu/2 |
#2 created | '2' |
Special Egg Pancake |
In the second step, the address is already /menu/2, but the page is still Chocolate Cheese Pancake. route.snapshot itself already holds the new id. What's stale (out of date) is the copy of the id you took once in ngOnInit.
When the page links to other ids, listen for the change with this.route.paramMap, without snapshot. This one is an Observable that sends the new parameters every time they change. In this code, menu and portions are kept in signals:
menu = signal<Menu | undefined>(undefined)
portions = signal(1)
ngOnInit() {
this.route.paramMap.subscribe((params) => {
this.menu.set(MENU.find((m) => m.id === Number(params.get('id'))))
})
this.route.queryParamMap.subscribe((query) => {
this.portions.set(Number(query.get('portions') ?? 1))
})
}
The template reads menu()?.name and portions(). Every time the parameter changes, the callback in subscribe runs again, the signals change, and the page changes with them. Why signals? Since Angular 22, components use OnPush by default: a component is only redrawn when something tells it to. A plain property replaced inside subscribe announces nothing, so the heading still shows the old pancake (tried in the exercise editor, Angular 22). You don't need to unsubscribe from the Observables of ActivatedRoute yourself: the router ends those subscriptions when the component is removed.
Query parameters: ?portions=2
A route parameter like /menu/2, also called a path parameter, says which item. The route doesn't match without it. A query parameter (?portions=2, ?sort=price) is only an extra note that may or may not be there.
- Read it with
queryParamMap.get('portions'):'2'when it's there,nullwhen it isn't. - It's text too.
'2' + 1gives'21', so convert it withNumber(...)first. - From code:
this.router.navigate(['/menu', 2], { queryParams: { portions: 2 } })opens/menu/2?portions=2.
The exercise: an id from the editor
The exercise editor has no route list. So the editor gives the component a fake active route (a route that acts as if it's showing the component) with the id 9f42c1. In the exercise, UserComponent only has to ask for ActivatedRoute, read paramMap.get('id') in ngOnInit (through snapshot or subscribe), and show it: <p>User ID: {{ userId }}</p> becomes User ID: 9f42c1.
💡 The id as an @Input
In an Angular CLI project, provideRouter(routes, withComponentInputBinding()) fills the @Input() id of a routed component (a component that a route shows) straight from the address. That input changes too when the parameter changes. The exercise editor and the Playground set up their own router without that feature, so here we use ActivatedRoute.
⚠️ A stale page, or an id that's null
- snapshot on a page that links to itself. From
/menu/1to/menu/2, the component is reused andngOnInitdoesn't run again. UseparamMap.subscribe(...). - A different parameter name. A
menu/:menuIdroute read withget('id')givesnull, and the page says "Menu not found". The name in the route and inget()must match exactly. - Forgetting the id is text. Convert it with
Number(id)before comparing it with a number or adding to it. - Exercise details. What's graded: there's a
<p>, the code containsActivatedRouteandparamMap, and the<p>contains9f42c1. That id must come from the route, not be typed into the template.
TL;DR: A route parameter is the part of an address whose content changes: the menu/:id route serves /menu/1, /menu/2 and so on with one component. That component reads its parameter through inject(ActivatedRoute), a service that holds details about the route now showing. There are two ways. snapshot.paramMap.get('id') reads the route's state once, in ngOnInit (a method Angular calls once after the component is created). paramMap.subscribe(...) listens for every change of the parameter. Use the second way when the page can move to another id, because the router reuses the same component and ngOnInit doesn't run again. A query parameter (?portions=2, an extra note in the address) is sent with [queryParams] and read with queryParamMap.get('portions'). Every value from the address is text or null, so convert it with Number(...) before doing math with it.
⚡ One route for many ids
Write:
{ path: 'menu/:id', component: MenuDetail },
Meaning: The colon in :id makes that part of the address a parameter: it can hold any value. So /menu/1, /menu/2 and /menu/3 are served by one component, MenuDetail (the pancake detail page). In the menu list's template, the links are built with [routerLink]="['/menu', m.id]", where m is one pancake in the @for.
⚡ Reading the id through ActivatedRoute
Write:
private route = inject(ActivatedRoute)
ngOnInit() {
const id = this.route.snapshot.paramMap.get('id') // '2', text
this.menu = MENU.find((m) => m.id === Number(id))
}
Meaning: ActivatedRoute is a service that holds details about the route showing this component. snapshot is the route's state at the moment you read it, and paramMap.get('id') takes the parameter named id. Angular calls ngOnInit once, after the component is created. A value from the address is always text, or null when there's no such parameter. So convert it with Number(id) before looking it up in MENU (the list of pancakes).
In the exercise, the editor gives a fake route with the id 9f42c1. Store that id in userId, and <p>User ID: {{ userId }}</p> becomes User ID: 9f42c1.
⚡ Moving to another id on the same page
Write:
this.route.paramMap.subscribe((params) => {
this.menu.set(MENU.find((m) => m.id === Number(params.get('id'))))
})
Guess first: say MenuDetail still uses the snapshot code from the step before. You're on /menu/1 and click a link to /menu/2 on the same page. Does the pancake name in the page's heading change?
No. The router reuses the same component, so ngOnInit doesn't run again, and the id copied there once is stale (out of date).
Meaning: this.route.paramMap, without snapshot, is an Observable that sends a new value every time the parameter changes. Keep the result in a signal (this.menu.set(...)) so the page changes too.