How to Get URL Parameters in Angular?

In Angular, you can get URL parameters using the ActivatedRoute module. Here is an example of how to do it:

Step1 – Import the ActivatedRoute module in your component:

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

Step 2 – Inject the ActivatedRoute service in the constructor:

constructor(private route: ActivatedRoute) { }

 

Step 3 – Use the route.paramMap property to access the URL parameters. For example, if the URL is http://example.com/users/42, you can access the 42 value like this:

ngOnInit() {
  const userId = this.route.snapshot.paramMap.get('id');
  console.log(userId); // Output: 42
}

 

Bonus Tip –  You can also use paramMap.getAll() to get all the params in the URL

ngOnInit() {
  const params = this.route.snapshot.paramMap;
  console.log(params.getAll());
}

 

Note that the route.snapshot property is used here to get the current value of the URL parameters. If you want to subscribe to changes in the URL parameters, you can use the route.paramMap.subscribe() method instead.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top