How To Get Route Path Parameters In Non-Routed Angular Components š¦
--
In this article weāre going to exploreā¦
- what are route path parameters
- how we can access route path parameters in a standard way
- what are the non-routed components
- why it is hard to access route path params in the non -routed components
- how to access them if we really need to
- other ways around the problem
- ā”StackBlitz working example of the described conceptsā¦
Letās go!
Angular routing is a very useful and powerful feature which usually ājust worksā as expected! However, there are some edge cases which deserves special attentionā¦
Imagine a following situation. We have an Angular application with some route and this route defines a path parameter usingĀ :id
in its route definition. The whole route path could look like the following /admin/user/:id
.
We can usually access this information in both sync and reactive ways in that particular component to which we navigated by injecting ActivatedRoute
and calling this.id$ = this.route.paramMap.pipe(paramMap => paramMap.get('id'))
or we can go with sync version and call this.id = this.route.snapshot.paramMap.get('id')
which is even simpler, right?
The choice between the Observable and sync snapshot retrieval of the path param depends on particular use case. We might need Observable if users can change url while application keeps displaying same component. In that case component has to keep reacting to the changes of the path parameter. This could for example mean that the component re-fetches data when the
id
in the url changesā¦
The Question
What if we wanted to know the value of the :
id
path parameter in a component which weā¦