Query Parameters
Why query parameters matter
Section titled “Why query parameters matter”Query parameters are the cheapest state container in a web application. Anything you put there is automatically shareable, bookmarkable, restored on refresh, and correct with the browser’s Back button — four properties that a service holding the same value gives you none of.
The decision rule is simple: if a user would reasonably send someone this link and expect them to see the same thing, the state belongs in the URL. Filters, sorting, pagination, the selected tab, an open detail panel — all yes. A hover state, a half-typed input, a transient toast — no.
Query params versus route params
Section titled “Query params versus route params”| Route param | Query param | |
|---|---|---|
| Syntax | /orders/42 |
/orders?status=open |
| Declared in the route config | Yes (path: 'orders/:id') |
No |
| Meaning | What resource | How you are viewing it |
| Optional | No — the path does not match without it | Yes |
| Survives navigation | No | Optionally, via queryParamsHandling |
If changing the value changes which resource you are looking at, it is a route param. If it changes the presentation of the same resource, it is a query param.
Reading them
Section titled “Reading them”As component inputs (preferred)
Section titled “As component inputs (preferred)”With withComponentInputBinding(), query params bind to inputs by name:
provideRouter(routes, withComponentInputBinding());@Component({ /* ... */ })export class OrderList { readonly status = input<string>('open'); readonly page = input(1, { transform: (v: string | undefined) => Number(v ?? 1) });
private readonly api = inject(OrderApiClient); readonly orders = httpResource<Order[]>( () => `/api/orders?status=${this.status()}&page=${this.page()}`, );}Two things to be careful about:
- The router assigns
undefinedwhen a param is absent. Either includeundefinedin the type, or normalise withtransformas above.input.requiredon a query param is almost always wrong, because query params are optional by nature. - Everything arrives as a string.
pagefrom the URL is'2', not2.transformis the right place to convert — and the right place to validate.
If you manage query params separately and do not want them bound, disable that half of the feature: withComponentInputBinding({ queryParams: false }).
Via ActivatedRoute
Section titled “Via ActivatedRoute”private readonly route = inject(ActivatedRoute);
readonly status = toSignal( this.route.queryParamMap.pipe(map((p) => p.get('status') ?? 'open')), { initialValue: 'open' },);Prefer queryParamMap over the raw queryParams object — it gives you get, has, and crucially getAll for repeated keys.
Do not read snapshot.queryParams in a component that stays mounted across query-param changes. Changing ?page=1 to ?page=2 does not recreate the component, so the snapshot is frozen at the first value.
Updating them
Section titled “Updating them”private readonly router = inject(Router);private readonly route = inject(ActivatedRoute);
setSort(sort: string): void { this.router.navigate([], { relativeTo: this.route, queryParams: { sort, page: 1 }, // changing sort resets pagination queryParamsHandling: 'merge', });}navigate([]) with relativeTo keeps the current path and changes only the query string.
queryParamsHandling
Section titled “queryParamsHandling”| Value | Behaviour |
|---|---|
| omitted | Replaces the entire query string with what you pass |
'merge' |
Merges your params into the existing ones |
'preserve' |
Keeps the existing params and ignores the ones you pass |
'merge' is what you want almost always. Omitting it is a common bug: setting ?sort=price silently drops ?status=open&page=3.
Setting a key to null or undefined under 'merge' removes it — that is how you clear a filter:
this.router.navigate([], { relativeTo: this.route, queryParams: { status: null }, queryParamsHandling: 'merge',});Do not flood the history stack
Section titled “Do not flood the history stack”A filter that navigates on every keystroke puts one history entry per character in the back stack. Use replaceUrl for continuous changes and normal navigation for discrete ones:
this.router.navigate([], { relativeTo: this.route, queryParams: { q: term }, queryParamsHandling: 'merge', replaceUrl: true, // update the URL without a new history entry});Rule of thumb: discrete choices (a tab, a page, a sort order) get a history entry; continuous input (a search box, a slider) replaces. Debounce the continuous ones too, or you serialise a navigation per keystroke.
In templates
Section titled “In templates”<a routerLink="/orders" [queryParams]="{ status: 'open' }" queryParamsHandling="merge" routerLinkActive="active"> Open orders</a>routerLink with [queryParams] produces a real <a href>, which means middle-click, open-in-new-tab and “copy link address” all work. A (click) handler calling router.navigate does not. For anything that is conceptually a link, use routerLink.
Typing and validating
Section titled “Typing and validating”The URL is user input. Anything can be in it, including values your code does not expect:
const STATUSES = ['open', 'shipped', 'cancelled'] as const;type Status = (typeof STATUSES)[number];
function toStatus(value: string | undefined): Status { return STATUSES.includes(value as Status) ? (value as Status) : 'open';}
@Component({ /* ... */ })export class OrderList { readonly status = input('open', { transform: toStatus }); readonly page = input(1, { transform: (v: string | undefined) => Math.max(1, Number(v) || 1), });}Normalising in a transform means the rest of the component never sees a bad value. Without it, ?page=-5 or ?page=abc reaches your API call — at best a wasted request, at worst an error page for a URL somebody shared.
Arrays and encoding
Section titled “Arrays and encoding”Repeated keys are the standard way to express a list:
/orders?tag=urgent&tag=exportreadonly tags = toSignal( this.route.queryParamMap.pipe(map((p) => p.getAll('tag'))), { initialValue: [] as string[] },);getAll is the only correct reader — get('tag') returns just one value. To write them, pass an array:
this.router.navigate([], { relativeTo: this.route, queryParams: { tag: ['urgent', 'export'] }, queryParamsHandling: 'merge',});Angular handles percent-encoding in both directions, so do not call encodeURIComponent yourself — you will double-encode. Two practical limits: URLs have length caps in the low thousands of characters in some proxies and browsers, so a query string is not a place for serialised objects; and a comma-separated single key (?tag=urgent,export) is a convention you then have to parse, split and escape yourself, which repeated keys give you for free.
Common mistakes
Section titled “Common mistakes”| Mistake | Consequence | Fix |
|---|---|---|
Omitting queryParamsHandling: 'merge' |
Other params silently dropped | Add 'merge' |
Reading snapshot.queryParams |
Frozen at the first value | queryParamMap, or component input binding |
| Trusting the value’s type | '2' is a string; 'abc' is possible |
Convert and validate in transform |
| Navigating per keystroke | History stack full of one-character states | replaceUrl: true plus a debounce |
get() on a repeated key |
Only the first value | getAll() |
encodeURIComponent before passing |
Double-encoded values | Let the router encode |
| Filters kept only in a service | Not shareable; lost on refresh | Put them in the URL |
(click) handler instead of routerLink |
No middle-click, no new tab, no copy link | Use routerLink with [queryParams] |
| Changing a filter without resetting the page | Page 7 of a 2-page result | Reset page whenever a filter changes |
Security and privacy
Section titled “Security and privacy”Query strings are not private. They are recorded in browser history, in server access logs, in proxy and CDN logs, in analytics, and they are sent in the Referer header to third-party origins the page links to or loads resources from.
Never put in a query parameter: authentication tokens, session identifiers, password-reset codes, email addresses or other personal identifiers, or anything else you would not want in a log file that many people can read.
Validate returnUrl before redirecting to it. The ?returnUrl= pattern used by login flows is a textbook open-redirect vector. Accept only same-origin relative paths:
function safeReturnUrl(value: string | null): string { return value && value.startsWith('/') && !value.startsWith('//') ? value : '/';}The // check matters — //evil.example is a protocol-relative URL to another origin that starts with a slash.
Query params are still just UI state. A ?admin=true that unlocks a screen is not a security control; every authorisation decision belongs on the server.