Passing Optional Parameters to a Route
Query parameters allow you to pass optional parameters to a route such as pagination information.
For example, on a route with a paginated list, the URL might look like the following to indicate that we've loaded the second page:
localhost:3000/product-list?page=2
The key difference between query parameters and route parameters is that route parameters are essential to determining route, whereas query parameters are optional.

Passing Query Parameters

Use the [queryParams] directive along with [routerLink] to pass query parameters. For example:
1
<a [routerLink]="['product-list']" [queryParams]="{ page: 99 }">Go to Page 99</a>
Copied!
Alternatively, we can navigate programmatically using the Router service:
1
goToPage(pageNum) {
2
this.router.navigate(['/product-list'], { queryParams: { page: pageNum } });
3
}
Copied!

Reading Query Parameters

Similar to reading route parameters, the Router service returns an Observable we can subscribe to to read the query parameters:
1
import { Component } from '@angular/core';
2
import { ActivatedRoute, Router } from '@angular/router';
3
4
@Component({
5
selector: 'product-list',
6
template: `<!-- Show product list -->`
7
})
8
export default class ProductList {
9
constructor(
10
private route: ActivatedRoute,
11
private router: Router) {}
12
13
ngOnInit() {
14
this.sub = this.route
15
.paramMap
16
.subscribe(params => {
17
// Defaults to 0 if no query param provided.
18
this.page = +params['page'] || 0;
19
});
20
}
21
22
ngOnDestroy() {
23
this.sub.unsubscribe();
24
}
25
26
nextPage() {
27
this.router.navigate(['product-list'], { queryParams: { page: this.page + 1 } });
28
}
29
}
Copied!
Last modified 9mo ago