Christian Giacomi

Angular, extract route parameter from Url

Posted — Jan 5, 2019

Angular is great, but some simple things seem to be more complicated than they actually are.

One of these is the way you can extract the id route parameter from a Url. There are many ways, and if you search on google you will really find tons of different ways, and it can sometimes be confusing. Especially when you start to see Observables mentioned.

Personally when I need to retrieve an id route parameter from a Url I always go with what I think is the simplest solution, and I follow the official Angular documentation.

In your component start by importing ActivatedRoute:

import { ActivatedRoute } from '@angular/router';

Then inject it in the constructor:

constructor(private route: ActivatedRoute) {}

And in OnInit() method you can then retrieve the route parameter like so:

ngOnInit(): void {
    const id = this.route.snapshot.paramMap.get('id');
}

This way you don’t need to worry about any Observables directly. Which makes your code more simple and readable.

If you would like to know more about routing you should take a look at the official Angular documentation.

If this post was helpful tweet it or share it.