Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 74 ยท Routing

Route Parameters, Query Params and Navigation

Read path and query parameters with input binding or ActivatedRoute, navigate from code with Router.navigate and relative links, and set page titles per route.

Real applications rarely have only fixed pages like /about. You need /courses/42 for course number 42, /search?q=signals&page=2 for a filtered list, and buttons that move the user somewhere after an action completes. Angular's router handles all three with path parameters, query parameters and programmatic navigation.

By the end of this lesson you'll know which kind of parameter to use, how to read it (the modern way with inputs, and the classic way with ActivatedRoute), how to navigate from code without getting the relative paths wrong, and how to give each page a sensible title. Make sure you've read Routing Basics first.

The real Angular code (routes, components, Router) is read-only here, because the site can't run the Angular compiler. The runnable examples are stand-ins: a route matcher that extracts parameters and a URL builder that resolves commands the way Router.navigate does. They show the logic, not the real router.

Path parameters

A path parameter is a variable segment of the URL. In the route table you mark it with a colon:

TypeScript
export const routes: Routes = [
  { path: 'courses', component: CourseListComponent },
  { path: 'courses/:id', component: CourseDetailComponent },
  { path: 'courses/:id/lessons/:lessonNo', component: LessonComponent },
];

The URL /courses/42 matches the second route with id equal to '42'. Two things to remember:

  • Parameters are always strings. Convert with Number(...) yourself and check for NaN.
  • Use a path parameter for identity: the thing the page is about. A course, a user, an order. Identity belongs in the path because it makes clean, shareable, cacheable URLs.

Query parameters

Query parameters come after ?: /courses?page=2&level=beginner. They aren't part of route matching, so they never change which component is shown. They're the right tool for optional state of a page: filters, sorting, pagination, a search term. Because they live in the URL, users can bookmark a filtered list or paste it to a colleague, and the browser's back button restores it.

A good rule of thumb: if removing the value would make it a different page, it's a path parameter; if it would just be the same page with different settings, it's a query parameter.

Reading parameters with component inputs

If you enabled withComponentInputBinding() in provideRouter, reading a parameter is as simple as declaring an input with the same name:

TypeScript
import { Component, computed, input } from '@angular/core';

@Component({
  selector: 'app-course-detail',
  template: `
    <h1>Course {{ id() }}</h1>
    <p>Showing page {{ page() }} of the lesson list.</p>
  `,
})
export class CourseDetailComponent {
  // from the path /courses/:id
  readonly id = input.required<string>();
  // from the query string ?page=2 (absent -> undefined)
  readonly pageParam = input<string | undefined>(undefined, { alias: 'page' });

  readonly page = computed(() => Number(this.pageParam() ?? '1') || 1);
}

The router sets inputs whose names match path parameters, query parameters, static data and resolved data of the route. Because they're signal inputs, computed values derived from them update automatically when the URL changes (see signals in components). Use alias when the URL name doesn't suit a class property name. Query parameters are optional, so type their inputs as possibly undefined.

Reading parameters with ActivatedRoute

Without input binding (or in older code), you inject ActivatedRoute, which describes the currently active route:

TypeScript
import { Component, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import { map } from 'rxjs';

@Component({
  selector: 'app-course-detail',
  template: `<h1>Course {{ id() }}</h1>`,
})
export class CourseDetailComponent {
  private readonly route = inject(ActivatedRoute);

  // 1. A one-time snapshot: fine only if the component is never reused
  readonly firstId = this.route.snapshot.paramMap.get('id');

  // 2. A stream that emits whenever the parameter changes
  readonly id = toSignal(this.route.paramMap.pipe(map((params) => params.get('id'))));
  readonly page = toSignal(this.route.queryParamMap.pipe(map((q) => q.get('page'))));
}

paramMap and queryParamMap are RxJS observables of ParamMap objects with get(), getAll() and has(). RxJS gets its own chapter; for now notice that toSignal turns the stream into a signal you can read in the template.

Why a snapshot can be wrong

When the user goes from /courses/1 to /courses/2, the route configuration is the same, so Angular reuses the existing component instance instead of destroying and recreating it. ngOnInit doesn't run again, and a value read once from snapshot is stale. Inputs and observables don't have this problem because they update when the URL does.

flowchart TD
  A["URL changes<br/>/courses/1 to /courses/2"] --> B{"Same route<br/>configuration?"}
  B -- "yes" --> C["Reuse the component instance"]
  C --> D["Inputs update, paramMap emits<br/>ngOnInit does not run again"]
  B -- "no" --> E["Destroy old component<br/>create new one"]

Changing only a parameter reuses the component, so read parameters reactively.

A runnable look at matching

The next example is a stand-in for the part of the router that turns a URL pattern like courses/:id into a parameter object. It splits both pattern and URL into segments, treats segments starting with : as variables and decodes them:

TypeScript Stand-in: extracting route parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice that the /courses and /courses/42 URLs matched different patterns even though one is a prefix of the other, and that the query string didn't affect matching at all. getAll('tag') is the stand-in for queryParamMap.getAll, which returns every value of a repeated key.

Links cover most navigation, but sometimes you move the user after something happens (a successful save, a login). Inject Router:

TypeScript
import { Component, inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({ selector: 'app-course-form', template: `...` })
export class CourseFormComponent {
  private readonly router = inject(Router);
  private readonly route = inject(ActivatedRoute);

  async saved(id: number): Promise<void> {
    // absolute: starts with "/"
    await this.router.navigate(['/courses', id]);

    // with query parameters
    await this.router.navigate(['/courses'], { queryParams: { page: 2, level: 'beginner' } });

    // relative to the current route
    await this.router.navigate(['lessons', 1], { relativeTo: this.route });

    // as one string
    await this.router.navigateByUrl('/courses/42?page=2');
  }

  nextPage(current: number): void {
    // keep other query params, change only page
    void this.router.navigate([], {
      relativeTo: this.route,
      queryParams: { page: current + 1 },
      queryParamsHandling: 'merge',
    });
  }
}

navigate takes an array of commands (each a segment) and returns a promise that resolves to true if navigation happened. navigateByUrl takes a complete URL string. Useful options:

  • relativeTo: the route that relative commands start from. Without it, relative commands are resolved from the root, a very common source of "why did it go to /lessons?" bugs.
  • queryParams and queryParamsHandling: 'merge' | 'preserve' to add to or keep the existing query string. Setting a parameter to null removes it when merging.
  • replaceUrl: true replaces the current history entry instead of adding one, good for redirects after login so Back doesn't return to the login form.

In templates, routerLink has matching inputs: [routerLink]="['/courses', id]", [queryParams]="{ page: 2 }" and queryParamsHandling="merge".

The URL-building rules are easy to experiment with in a stand-in. Commands are appended segment by segment, .. goes up one level, and relative commands only make sense with a starting point:

TypeScript Stand-in: resolving navigation commands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The fourth line shows the relative-navigation trap: without relativeTo, ['lessons'] becomes /lessons. The last two lines show merge keeping sort while changing page, and null removing a parameter.

Setting page titles

A route's title property sets document.title when it becomes active. It can be a fixed string, or a function that runs in an injection context and can return a string or a promise or observable of one:

TypeScript
import { ResolveFn, Routes } from '@angular/router';
import { inject } from '@angular/core';
import { CourseService } from './course.service';

const courseTitle: ResolveFn<string> = async (route) => {
  const course = await inject(CourseService).load(route.paramMap.get('id') ?? '');
  return `${course.title} | Learn Angular`;
};

export const routes: Routes = [
  { path: 'courses', component: CourseListComponent, title: 'All courses' },
  { path: 'courses/:id', component: CourseDetailComponent, title: courseTitle },
];

To add a site-wide suffix to every title, extend TitleStrategy and override updateTitle, then register it with { provide: TitleStrategy, useClass: AppTitleStrategy } in your providers. Inside it you call this.buildTitle(snapshot) to get the title the active route produced. Descriptive titles matter for accessibility (screen readers announce them on navigation) and for search engines, so avoid leaving every page as "MyApp". Dependency injection is what makes the strategy swap possible.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which belongs in a query parameter rather than a path parameter?

    Page and sort are optional settings of the same page, so they fit the query string. The identity of the thing shown (course, user, order) belongs in the path.
  2. 2. You navigate from /courses/1 to /courses/2 and the component still shows course 1. What is the most likely cause?

    Same route configuration means the same component instance, and ngOnInit does not run again. Reading paramMap, using toSignal or using inputs keeps the value current.
  3. 3. What does router.navigate(['lessons']) do when you don't pass relativeTo?

    Relative commands are resolved from the root unless you provide relativeTo with an ActivatedRoute.
  4. 4. What type do values read from path parameters have?

    Parameters come from the URL, so they are strings. Convert and validate them yourself.
  5. 5. What does queryParamsHandling "merge" do?

    Merge combines the new queryParams with the existing ones; passing null for a key removes it.

Summary

  • Path parameters (courses/:id) identify the page's subject and are always strings; query parameters carry optional state like filters and pages.
  • With withComponentInputBinding(), routed components receive path params, query params, data and resolved data as input()s.
  • Otherwise use ActivatedRoute: paramMap and queryParamMap are observables, and snapshot is only safe when the component is never reused. toSignal bridges to signals.
  • Navigate from code with Router.navigate([...commands], extras) or navigateByUrl; use relativeTo for relative commands and queryParamsHandling: 'merge' to keep other query parameters.
  • title (a string or a resolver function) sets the tab title, and a custom TitleStrategy applies site-wide rules.
  • The Angular code here is read-only; the runnable examples are stand-ins for matching and URL building.

Next: Child Routes and Lazy Loading