Reading Query Parameters

Input binding hands query parameters to the page as inputs too, or undefined when they're missing, so give each a default with ?? in a computed. Link with routerLink and [queryParams], and change them from code with navigate and queryParamsHandling 'merge'.

Journeyman · Angular · Updated

After this lesson you can

  • Read query parameters as component inputs, with a default when they're missing
  • Link and navigate with query parameters

Key takeaways

  • With withComponentInputBinding(), query parameters arrive as ordinary input()s, and they're undefined when missing.
  • Give a missing query parameter its default with ??, as in Number(this.page() ?? 1). A default in input('1') doesn't work: the router sets a missing one to undefined.
  • Query parameters are strings, so turn them into numbers before doing sums with them.
  • [queryParams]="{ categoryId: 8 }" adds query parameters to a routerLink.
  • navigate with queryParamsHandling: 'merge' changes one query parameter and keeps the rest; without it, the new ones replace the old.

The products page will read two query parameters: categoryId, to show one category's products, and page, to show ten products at a time. It uses the ProductApi service from Exercise: an Angular Client for a Web API, whose getAll(categoryId) loads all the products, or one category's.

Query parameters as inputs

withComponentInputBinding(), from Reading the Route Parameter, hands query parameters to the page as inputs too, by name. They're optional, so they're ordinary input()s, not input.required():

import { Component, computed, effect, inject, input, signal } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { Router, RouterLink } from '@angular/router';
import { Product } from './product';
import { ProductApi } from './product-api';

@Component({
  imports: [CurrencyPipe, RouterLink],
  selector: 'app-products-page',
  template: `
    <h1>Products</h1>
    <nav class="nav nav-pills mb-3">
      <a class="nav-link" routerLink="/products">All</a>
      <a class="nav-link" routerLink="/products" [queryParams]="{ categoryId: 1 }">Beverages</a>
      <a class="nav-link" routerLink="/products" [queryParams]="{ categoryId: 8 }">Seafood</a>
    </nav>
    <ul class="list-group mb-3">
      @for (product of shown(); track product.productId) {
        <li class="list-group-item">{{ product.productName }}, {{ product.unitPrice | currency }}</li>
      }
    </ul>
    <button class="btn btn-outline-primary" [disabled]="pageNumber() === 1" (click)="goToPage(pageNumber() - 1)">Previous</button>
    <span class="mx-3">Page {{ pageNumber() }}</span>
    <button class="btn btn-outline-primary" [disabled]="pageNumber() * 10 >= products().length" (click)="goToPage(pageNumber() + 1)">Next</button>
  `,
})
export class ProductsPage {
  private readonly api = inject(ProductApi);
  private readonly router = inject(Router);

  readonly categoryId = input<string>();
  readonly page = input<string>();

  protected readonly pageNumber = computed(() => Number(this.page() ?? 1));
  protected readonly products = signal<Product[]>([]);
  protected readonly shown = computed(() => this.products().slice((this.pageNumber() - 1) * 10, this.pageNumber() * 10));

  constructor() {
    effect(() => {
      const categoryId = this.categoryId();
      this.api.getAll(categoryId === undefined ? undefined : Number(categoryId))
        .subscribe(products => this.products.set(products));
    });
  }

  protected goToPage(page: number) {
    this.router.navigate(['/products'], { queryParams: { page }, queryParamsHandling: 'merge' });
  }
}
Address categoryId() page() pageNumber()
/products undefined undefined 1
/products?categoryId=8 '8' undefined 1
/products?categoryId=1&page=2 '1' '2' 2

Defaults

A missing query parameter is undefined. So give it its default where you use it: this.page() ?? 1 is the page, or 1 when there's none, and pageNumber is a computed, so it follows the address.

You might try a default in the input itself, input('1'). It doesn't work: when the parameter is missing, the router sets the input to undefined, and the default is lost. Use ??.

Like route parameters, query parameters are strings, '2', so turn them into numbers before doing sums with them.

And as with a route parameter, going from ?page=1 to ?page=2 keeps the same ProductsPage on screen, and only changes its inputs. The effect reloads the products when categoryId changes, and shown follows pageNumber by itself.

Links with query parameters

[queryParams] adds query parameters to a routerLink:

<a routerLink="/products" [queryParams]="{ categoryId: 8 }">Seafood</a>

makes /products?categoryId=8. The All link has no query parameters, so it's plain /products. Clicking Seafood on page 2 starts again at page 1, because the link's address has no page. That's what you want after changing the filter.

Changing them from code

navigate takes queryParams too. The Next and Previous buttons change only the page, and keep the category, with queryParamsHandling: 'merge': it mixes the new query parameters into the ones already in the address.

On Click Without merge With merge
/products?categoryId=1 Next /products?page=2 /products?categoryId=1&page=2
/products?categoryId=1&page=2 Previous /products?page=1 /products?categoryId=1&page=1

Without merge, the new query parameters replace the old ones, and the category is lost.

Try it

With the API running, open http://localhost:4200/products: page 1 of all 77 products. Click Next twice, and the address says ?page=3. Copy the address into a new tab: the same page opens, because everything the page needs is in the address. Click Beverages: you're back on page 1, of its twelve products. Click Next: the last two, the address keeps categoryId=1 and adds page=2, and Next is disabled.

Do it: show one page of products

The products page shows ten products at a time, and reads which page to show from the page query parameter. Write the part that picks the page's products, in plain JavaScript.

The function gets two values:

  • products: the products' names, in order, a list of strings.
  • page: the page query parameter as the page gets it: a string ('2'), or undefined when the address has no page.

For example, the twelve Beverages, page '2':

const beverages = ['Chai', 'Chang', 'Guaraná Fantástica', 'Sasquatch Ale', 'Steeleye Stout', 'Côte de Blaye',
  'Chartreuse verte', 'Ipoh Coffee', 'Laughing Lumberjack Lager', 'Outback Lager', 'Rhönbräu Klosterbier', 'Lakkalikööri'];
Step Here
The page, as a number '2' becomes 2
Its first product's place (2 − 1) × 10 = 10
Up to, not including, place 2 × 10 = 20
The products at places 10 to 19 'Rhönbräu Klosterbier', 'Lakkalikööri' (there are only 12)

So productsOnPage(beverages, '2') returns ['Rhönbräu Klosterbier', 'Lakkalikööri'].

Your job: write the function productsOnPage(products, page), which returns the list of names on that page.

  • Ten products a page: page 1 is places 0 to 9, page 2 is places 10 to 19, and so on.
  • page is a string: turn it into a number before doing sums with it.
  • When page is undefined, show page 1.
  • A page after the last product gives an empty list, [].

Practiced live on the lesson page: write the JavaScript right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

Query parameters arrive as optional inputs, undefined when missing, so ?? gives them defaults. [queryParams] puts them in links, and navigate with merge changes one and keeps the rest: a page whose whole state can be bookmarked and shared.

Key terms

Cheat sheets