Angular 16 Preview: Binding Router Information to Component Inputs

Passing parameters to routes is a frequent task with Angular. Before Angular 16, we had to inject the ActivatedRoute service and retrieve the parameters from that service using the snapshot or params properties.

With Angular 16, we can get those values automatically bound to the component inputs using the following router config:

If you’re using the RouterModule.forRoot() syntax, then enabling component input binding looks like this:

RouterModule.forRoot(routes, {bindToComponentInputs: true});Code language: JavaScript (javascript)

According to the documentation, this option can bind all route data with key-value pairs to component inputs: static or resolved route data, path parameters, matrix parameters, and query parameters.

For instance, assuming we have a URL parameter called id, if we enable the component input binding feature, then all we need in our component is an @Input decorator to receive that value:

What I like about this option is that our components do not need the ActivatedRoute service anymore, meaning they don’t have to be used just as routed components. Instead, they could be used in other scenarios where the id is passed as an HTML attribute, just like any other non-routed component. As a result, our components are more generic and not tied to a single use case.

Angular 16 Preview: Required Inputs

The @Input decorator plays an essential role in the Angular framework as such inputs for presentation components allow us to fine-tune application performance by using the onPush change detection strategy.

Earlier in this newsletter, we also talked about how inputs justified the existence of the ngOnInit lifecycle hook.

Inputs are about to become even better in Angular 16 with the addition of required inputs that would throw a compile-time error when an input for a component/directive is required but not set:

The syntax is easy to remember, too. Angular 16 is scheduled to be released this week, and I’ll be posting more new features of that new version all week long.

The main feature of v16 will be Angular Signals, so I just released a short video course to learn all you need to know about Angular Signals for just $9!