← Back to Angular, page 3

angular-0054 · Easy fresher

What is the difference between route parameters, query parameters and fragments, and how do you read and change them?

Route parameters are part of the path (/courses/42) and identify a resource. Query parameters come after a question mark (?page=2&sort=name) and describe optional state such as filters. A fragment follows a hash. Read them with input binding or ActivatedRoute, and change them with routerLink or Router.navigate.

Full answer

Take the URL /courses/42?page=2&sort=name#reviews.

  • Route parameter id = 42. It is declared in the route path (courses/:id). It is required, because without it the route does not match. Use it for identity.
  • Query parameters page = 2 and sort = name. They are optional and are not part of route matching. Use them for filters, sorting, and paging, so a user can share or bookmark the filtered view.
  • Fragment reviews. Used for in-page anchors.

Reading them:

  • With withComponentInputBinding() in provideRouter, route parameters and query parameters are set on component inputs with the same name: id = input.required<string>() and page = input<string>().
  • With ActivatedRoute: route.paramMap and route.queryParamMap are Observables. route.snapshot.paramMap is a one-time read. Use the Observable when the same component instance is reused for different ids, for example when going from /courses/1 to /courses/2, because the snapshot does not change.
  • toSignal(route.queryParamMap) converts it to a signal.

Changing them:

  • Template: <a [routerLink]="['/courses', id]" [queryParams]="{ page: 3 }" queryParamsHandling="merge">.
  • Code: router.navigate([], { relativeTo: route, queryParams: { page: 3 }, queryParamsHandling: 'merge' }). With an empty command array it stays on the same route and only changes the query. merge keeps the other query parameters, and preserve keeps all of them.

Remember that all parameter values are strings. Convert numbers yourself, and validate them, since users can edit the URL.

typescript
import { Component, computed, inject, input } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { map } from 'rxjs';

@Component({
  selector: 'app-course-page',
  imports: [RouterLink],
  template: `
    <h1>Course {{ id() }}</h1>
    <p>Page {{ page() }}, sorted by {{ sort() }}</p>
    <button (click)="goToPage(page() + 1)">Next page</button>
    <a [routerLink]="[]" [queryParams]="{ sort: 'name' }" queryParamsHandling="merge">Sort by name</a>
  `,
})
export class CoursePageComponent {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);

  // Route parameter (courses/:id), bound by withComponentInputBinding().
  readonly id = input.required<string>();

  // Query parameters read through ActivatedRoute. Values are strings.
  private readonly query = toSignal(this.route.queryParamMap.pipe(map((q) => ({ page: q.get('page'), sort: q.get('sort') }))), {
    initialValue: { page: null, sort: null },
  });

  readonly page = computed(() => {
    const n = Number(this.query().page);
    return Number.isInteger(n) && n > 0 ? n : 1;
  });
  readonly sort = computed(() => this.query().sort ?? 'date');

  goToPage(page: number): void {
    void this.router.navigate([], {
      relativeTo: this.route,
      queryParams: { page },
      queryParamsHandling: 'merge',
    });
  }
}

Angular 20.3, strict template check passes. The component works at a path like `courses/:id` when the router uses `withComponentInputBinding()`.

Key points

  • Route params identify the resource. Query params hold optional state. The fragment is an anchor.
  • Read with input binding (`withComponentInputBinding`) or with `ActivatedRoute` observables.
  • Use `queryParamsHandling: 'merge'` to change one query parameter and keep the others.
  • Values are strings and can be edited by the user, so validate them.

Common mistakes

  • Using `route.snapshot` in a component that is reused for different ids, so the page does not update.
  • Navigating with `queryParams` without `merge`, which drops the other filters.
  • Treating `page` as a number without converting it.

Follow-ups

  • Why does Angular reuse the component when only the id changes?
  • When would you store state in the query string instead of a service?
  • How do you read matrix parameters?

Tips

  • Use the filter and paging example for query parameters. It shows a clear reason: shareable URLs.
  • Mention reuse of component instances. It is the classic bug.
  • Say that you validate and convert values.

Evaluation rubric

  • Distinguishes the three parts of a URL.
  • Reads and updates parameters with current APIs.
  • Understands snapshot versus observable.