Reading the Route Parameter

With withComponentInputBinding, the router hands a route's parameters to the page component as inputs, so categoryId is an input like any other, turned into a number with numberAttribute. Load the data in an effect, because Angular reuses the page when only the id changes.

Journeyman · Angular · Updated

After this lesson you can

  • Read a route parameter as a component input, and load the data it names

Key takeaways

  • withComponentInputBinding() in app.config.ts lets the router hand a route parameter to the page as an input with the same name.
  • input.required({ transform: numberAttribute }) turns the parameter's string, '3', into the number 3.
  • Load the data in an effect, not ngOnInit: Angular reuses the page when only the id changes, and the effect runs again for the new id.
  • ActivatedRoute's snapshot.paramMap is the older way to read a parameter, and it misses a change of id on the same page.

The route categories/:categoryId shows CategoryDetails. Now the component needs the id, to load that category from the API.

Parameters as inputs

The simplest way: let the router hand the parameter to the component as an input. Switch it on once, in app.config.ts, with withComponentInputBinding():

import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes, withComponentInputBinding())
  ]
};

Now, when the router shows a page, it sets each input whose name matches a parameter. Give CategoryDetails an input named exactly like the parameter, categoryId:

import { Component, effect, inject, input, numberAttribute, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import { Category, CategoryApi } from './category-api';

@Component({
  imports: [RouterLink],
  selector: 'app-category-details',
  template: `
    @if (category(); as category) {
      <h1>{{ category.categoryName }}</h1>
      <p>{{ category.description }}</p>
    } @else {
      <p>Loading category {{ categoryId() }}...</p>
    }
    <a routerLink="/categories">All categories</a>
  `,
})
export class CategoryDetails {
  private readonly api = inject(CategoryApi);

  readonly categoryId = input.required({ transform: numberAttribute });
  protected readonly category = signal<Category | undefined>(undefined);

  constructor() {
    effect(() => {
      this.category.set(undefined);
      this.api.getById(this.categoryId()).subscribe(category => this.category.set(category));
    });
  }
}

At /categories/3, the router sets categoryId to 3, the effect loads category 3, and the page shows Confections.

  • input.required(...): the route always has the parameter, so the input is never missing.
  • transform: numberAttribute turns the string from the address, '3', into the number 3. A value that isn't a number, such as /categories/cheese, becomes NaN. The API answers that with an error, so use the last chapter's error handling to show a message.
  • @if (category(); as category) shows the category once it has arrived, under the short name category, and Loading... until then.

Why an effect, not ngOnInit?

You might load the category in ngOnInit. That works when you come from the list. But when you go from /categories/3 to /categories/4, from a Next category link on the page, say, Angular reuses the CategoryDetails already on screen, because it's the same route. It only changes the input. ngOnInit doesn't run again, so the page would keep showing category 3.

An effect runs again whenever a signal it reads changes. It reads categoryId(), so a new id loads the new category, whichever way you arrived. (set(undefined) first shows Loading... while the new one is on its way.)

The other way: ActivatedRoute

In code written before input binding, and in many tutorials, you'll see the parameter read from the ActivatedRoute, the router's description of the page that's showing:

private readonly route = inject(ActivatedRoute);

ngOnInit() {
  const categoryId = Number(this.route.snapshot.paramMap.get('categoryId'));
  // ...load the category
}

snapshot.paramMap.get('categoryId') gives the parameter as a string, '3'. It's a snapshot: the values when the page opened. Like ngOnInit, it misses a change of id on the same page. ActivatedRoute also has observables that do follow the changes, but input binding does the same job with less code.

Check yourself

1 question to try on the lesson page.

So what

With withComponentInputBinding(), a route parameter is just an input with the same name. Turn it into a number, and load its data in an effect, so the page follows the id wherever it changes.

Key terms

Cheat sheets