Sub topic 7
Working with Query Parameters and Fragments
Route parameters identify which resource a view shows, for example the 42 in /products/42. Query parameters and fragments describe how to show it: the active filter, the sort order, the current page, or the section the user should land on. This chapter shows how to set them, read them, keep them across navigations, and avoid the mistakes that come up most often.
The chapter assumes you already know standalone components, inject(), basic RxJS Observables, and the route parameter material from the previous chapter, including ActivatedRoute and withComponentInputBinding. Router.navigate gets its own chapter next. It appears here only where query parameters need it.
Anatomy of a URL the Router Sees
Take this URL:
/products?category=books&tag=new&tag=sale&page=2#reviews
The Router splits it into three parts, and each part has its own job:
| Part | Example | Used for route matching? | Where you read it |
|---|---|---|---|
| Path | `/products` | Yes | `paramMap`, component inputs |
| Query string | `?category=books&tag=new&tag=sale&page=2` | No | `queryParamMap`, component inputs |
| Fragment | `#reviews` | No | `fragment` |
Query parameters and fragments never affect which route matches. A route declared as { path: 'products', component: ProductListComponent } matches /products, /products?page=9, and /products#top in exactly the same way. Query parameters also belong to the whole URL rather than to one route segment, so every ActivatedRoute in the tree (parent, child, or grandchild) sees the same query parameters.
Setting Query Parameters and Fragments with RouterLink
RouterLink takes two extra inputs, queryParams and fragment, alongside the path commands.
import { Component } from '@angular/core';
import { RouterLink } from '@angular/router';
@Component({
selector: 'app-product-filters',
standalone: true,
imports: [RouterLink],
template: `
<!-- /products?category=books&page=1 -->
<a routerLink="/products" [queryParams]="{ category: 'books', page: 1 }">Books</a>
<!-- /products?tag=new&tag=sale -->
<a routerLink="/products" [queryParams]="{ tag: ['new', 'sale'] }">New and on sale</a>
<!-- Stay on the current route, change only the page, keep other params -->
<a [routerLink]="[]" [queryParams]="{ page: 2 }" queryParamsHandling="merge">Page 2</a>
<!-- /products/42#reviews -->
<a [routerLink]="['/products', 42]" fragment="reviews">Read reviews</a>
`
})
export class ProductFiltersComponent {}Some details in this example:
- Values can be strings, numbers, or booleans. The Router turns them into strings and URL-encodes them for you, so
{ q: 'a&b' }becomes?q=a%26b. - An array value repeats the key:
tag=new&tag=sale. [routerLink]="[]"means "the current route". It is the usual way to change only the query string.
Controlling What Happens to Existing Query Parameters
By default, every navigation replaces the whole query string. The queryParamsHandling option changes that:
| Value | Behavior | Typical use |
|---|---|---|
| `''` (default) | Use only the new `queryParams`; drop the current ones | Moving to an unrelated page |
| `'merge'` | Combine current and new; new values win on conflicts | Changing one filter while keeping the rest |
| `'preserve'` | Keep the current query string; ignore new `queryParams` | Carrying context, such as `?returnUrl=...`, through a flow |
Fragments work the same way. Without a fragment input the fragment is dropped. Add preserveFragment (for example <a routerLink="/faq" preserveFragment>) to keep the current one.
Reading Query Parameters with ActivatedRoute
ActivatedRoute exposes queryParamMap (an Observable of ParamMap) and fragment (an Observable of string | null). Converting them to signals keeps the template simple.
import { Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { map } from 'rxjs';
@Component({
selector: 'app-product-list',
standalone: true,
imports: [RouterLink],
template: `
<h2>Category: {{ category() }}, page {{ page() }}</h2>
<p>Tags: {{ tags().join(', ') || 'none' }}</p>
@for (t of tags(); track t) {
<button (click)="removeTag(t)">Remove {{ t }}</button>
}
@if (fragment()) {
<p>Linked section: {{ fragment() }}</p>
}
<a [routerLink]="[]" [queryParams]="{ page: nextPage() }" queryParamsHandling="merge">Next</a>
`
})
export class ProductListComponent {
private route = inject(ActivatedRoute);
private router = inject(Router);
private params = toSignal(this.route.queryParamMap, {
initialValue: this.route.snapshot.queryParamMap
});
readonly category = computed(() => this.params().get('category') ?? 'all');
readonly page = computed(() => {
const n = Number(this.params().get('page'));
return Number.isInteger(n) && n > 0 ? n : 1;
});
readonly tags = computed(() => this.params().getAll('tag'));
readonly nextPage = computed(() => this.page() + 1);
readonly fragment = toSignal(this.route.fragment, {
initialValue: this.route.snapshot.fragment
});
removeTag(tag: string): void {
const remaining = this.tags().filter(t => t !== tag);
this.router.navigate([], {
relativeTo: this.route,
queryParams: { tag: remaining.length ? remaining : null },
queryParamsHandling: 'merge'
});
}
}Three habits in this code prevent most bugs:
- Always parse and validate.
get()returnsstring | null. A user can type?page=bananaor?page=-3, so treat the query string as untrusted input and fall back to a safe default. - Use
getAll()for repeated keys.get('tag')returns only the first value.getAll('tag')returns astring[], and the array is empty when the key is missing. - Subscribe instead of reading the snapshot. When only the query string changes, the Router reuses the existing component instance.
route.snapshot.queryParamMapis a one-time read and goes stale after that. The observable emits on every change.
Binding Query Parameters to Component Inputs
If the router is registered with withComponentInputBinding(), query parameters are bound to inputs with matching names, just like path parameters are.
import { Component, Input, booleanAttribute, numberAttribute } from '@angular/core';
@Component({
selector: 'app-search-results',
standalone: true,
template: `<p>Searching "{{ q }}", page {{ page }}, in stock only: {{ inStock }}</p>`
})
export class SearchResultsComponent {
@Input() q = '';
@Input({ transform: numberAttribute }) page = 1;
@Input({ transform: booleanAttribute }) inStock = false;
}For /search?q=lamp&page=3&inStock=true, the inputs receive 'lamp', 3, and true. Keep these behaviors in mind:
- A key that is missing from the URL sets the input to
undefined, which overwrites the field initializer. Use a transform or a setter if you need a default to survive. - The binding does not check types. Without a transform,
pagewould be the string'3'even though it is declared as a number. - If a path parameter, a query parameter, and route
datashare a name, only one value reaches the input. Choose distinct names. - Fragments are not bound to inputs. Read them from
ActivatedRoute.fragment. numberAttributereturnsNaNfor values such as?page=banana, so it does not replace the validation shown earlier when the value matters.
Scrolling to Fragments
By default, the Router updates the fragment but does not scroll to it. Enable anchor scrolling when you register the router:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, withComponentInputBinding, withInMemoryScrolling } from '@angular/router';
import { AppComponent } from './app.component';
import { routes } from './app.routes';
bootstrapApplication(AppComponent, {
providers: [
provideRouter(
routes,
withComponentInputBinding(),
withInMemoryScrolling({
anchorScrolling: 'enabled',
scrollPositionRestoration: 'enabled'
})
)
]
});With this setup, navigating to /products/42#reviews scrolls to the element whose id is reviews. Two caveats apply:
- The scroll runs when navigation finishes. If
#reviewsis inside content that renders later, such as after an HTTP request, the element does not exist yet and nothing happens. In that case, scroll yourself withViewportScroller.scrollToAnchor()once the content has loaded. - Plain
<a href="#reviews">links resolve against the<base href="/">tag. On/products/42, such a link sends the user to/#reviews, which is a different route. UserouterLinkwithfragmentinstead.
Common Errors at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| Filters reset when changing page | Default handling replaced the query string | Add `queryParamsHandling="merge"` |
| View doesn't update on `?page=2` → `?page=3` | Code reads `snapshot` once | Subscribe to `queryParamMap` |
| `page + 1` gives `"21"` | Values are strings | Convert with `Number()` and validate |
| Only one tag is read | `get()` used on a repeated key | Use `getAll()` |
| Fragment link reloads home | Plain `href="#x"` with a base href | Use `routerLink` + `fragment` |
| No scroll to `#section` | Anchor scrolling is off | `withInMemoryScrolling({ anchorScrolling: 'enabled' })` |
Exercise
The current URL is /products?category=books&page=4. A link is written as <a [routerLink]="[]" [queryParams]="{ page: 1, sort: 'price' }">. What URL results, and what one change would make the link keep the category?
Show answer
The link produces /products?page=1&sort=price, because the default queryParamsHandling replaces the whole query string and drops category. Adding queryParamsHandling="merge" produces /products?category=books&page=1&sort=price.
Exercise
A component sets this.page = Number(this.route.snapshot.queryParamMap.get('page')) in its constructor. Users report that the page number shown stays the same when they click Next, even though the URL changes. Explain why, and give a fix.
Show answer
Changing only the query string reuses the same component instance, so the constructor does not run again and the snapshot value is never re-read. Derive page from the route.queryParamMap observable instead, for example with toSignal plus computed, or bind it as an input through withComponentInputBinding. Also validate the parsed number.
Exercise
With queryParamsHandling 'merge', how do you remove the tag parameter entirely, and what goes wrong if you set it to an empty string?
Show answer
Set tag to null (or undefined) in queryParams. The Router then omits the key. An empty string keeps the key as ?tag=, so get('tag') returns '' and getAll('tag') returns [''], which reading code may treat as a real tag.