Stop, don’t use ActivatedRoute anymore to get your route data!

Carlos Torres
3 min readNov 2, 2023

--

With the arrival of Angular 16, many very interesting features have been added to push our code to the next level.

One of these features is the automatic mapping of the data obtained from the routes through the well-known @Input decorator that decorator that Angular offers and that we usually import into the child components.

If we wanted to read certain information from a resolver, for example, we did it in the following way:

We declare our routes file and in /products we place a resolver so that the server is queried for the products and returns that information in the products variable before the component is initialized.

Before

Upon declaring the resolver, the subsequent action within our ProductsComponent is to create a subscription to the ActivatedRoute. This subscription is essential for extracting the value passed by the resolver, facilitating the configuration of our component’s product array.

Now

Angular 16 introduces a new property known as bindToComponentInputs.

The bindToComponentInputs property is a fresh addition in Angular version 16, enabling the automatic binding of router information, including query parameters, route parameters, static data, and resolver data, to the inputs of a routed component.

It is crucial to place this property within the routes of the root module so that all child components can leverage this innovative feature.

It’s evident that the property is placed within the .forRoot() method. In the case of routes defined using .forChild(), adding this property is not feasible because .forChild() accepts only one parameter, which is the route configuration file, making it impossible to pass a second configuration parameter.

Once this property is set to true, the next step is to refactor the code as follows:

Please note that the Input() variable should be declared with the same name as specified in the route configuration file. In this example, we’re using “products” as the variable to be returned by the resolver. By doing this, automatic mapping is valid, and the information will be stored directly within that variable.

And there you have it! We’ve eliminated the need to import the ActivatedRoute service from @angular/core, and we’ve also removed the subscription. As a result, the code is now cleaner and more readable. Just imagine if you had 1, 2, or 3 resolvers… It would become quite chaotic.

…Additional Information

This isn’t limited to just resolvers; as mentioned earlier, it also applies to parameters such as data, title, queryParams, pathParams, and so on. These can all be automatically mapped using @Input, eliminating the need to inject the ActivatedRoute class.

Follow me on Medium to read more about Angular and JavaScript

Happy coding!

--

--