The Angular router comes with many interesting features, such as lazy-loading, guards, resolvers, or nested routes.
One of these features is the ability to access route parameters and route information within the component displayed by the router. This can be done by injecting the ActivatedRoute
service in our component.
This ActivatedRoute
contains a lot of information:
The most commonly used attributes are:
paramMap
: An Observable of route parameters such asid
in the route/product/:id/info
queryParamMap
: An Observable of query parameters such asq
in the route/product/search?q=test
data
: An Observable of the data resolved by route resolvers such ashero
in this example of a resolver.
snapshot
gives us the current value of those same parameters instead of using Observables.
Another option appeared with Angular 16. We can bind router information to component inputs instead of using ActivatedRoute
.
This works for the three categories of parameters covered earlier: Route params, query params, and resolved route data.
This means that this old and verbose approach:
can be replaced with the following concise and router-independent code:
The only config needed for this to work is the one line of code described in this article.