injectParams

The injectParams function is a versatile utility for injecting and transforming route parameters within an Angular application. It provides a reactive way to access and manipulate route parameters using Angular's signals-based architecture, making it easier to handle dynamic routing scenarios.

Usage

  • When called without any arguments, injectParams returns a signal containing the entire params object of the current route. This is useful when multiple parameters need to be accessed or processed.
  • When a key is specified, injectParams returns the value of the corresponding parameter as a signal. If the parameter is not present, null is returned. This is useful for accessing individual parameters directly.
  • To transform the parameters, you can either pass a transform function as the first argument, or pass it in the optionstransform property.
  • Options not only contains the transform function, but also the initialValue. If the initialValue type is a boolean or number, transform function must be provided.
import {numberAttribute, Signal} from '@angular/core';
import {injectParams} from 'ngx-lift';

export class InjectParamsComponent {
  // returns a signal with the current route params
  params = injectParams();

  // returns a signal with the keys of the params
  paramsKeys = injectParams((params) => Object.keys(params));

  // returns a signal with the value of the id param
  userId: Signal<string | null> = injectParams('id');

  // returns a signal with the value of the id param, initialValue is 1
  id: Signal<number> = injectParams('id', {transform: numberAttribute, initialValue: 1})

  // pass a transform function directly
  name = injectParams((params) => params['name'] as string);

  // whenever userId param is changed, fetch the user
  user = computedAsync(() => this.userService.getUser(this.userId()));
}