As an Angular developer, you'll find it's often the case that you need to send users to a route with query parameters.

For example, if the user needs to view a specific contact in a CRM application. Usually, you'll send the user to a route that looks like this: /contacts/view-contact?id=21

Well that's fine and dandy... but how does the component that handles that route retrieve the query parameter?

In this guide, I'll answer that question.

Activate Your Route

What you're going to need here is a service called ActivatedRoute. It will give you info about a route associated with a component.

In this case, you'll use it to get the query parameters.

As I mentioned above, though, ActivatedRoute is a service. So you'll need to inject it into your component with the constructor. 

constructor(private activatedRoute: ActivatedRoute) { }

Now that you have access to the ActivatedRoute service, you can use it to get parameters.

But...

The ActivatedRoute service provides access to query parameters via an Observable. So you gotta do some subscribin' if you want to get those params.

Here's what I've got for a quick and dirty test:

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe(params => {
      console.log(params['id']);
    });
  }

That will run once the component is loaded because it's in the ngOnInit() method. 

The code above grabs the queryParams property (an Observable)  from the ActivatedRoute service. Then it subscribes and retrieves the parameters as they get emitted.

In the example above, the code is looking for a parameter called "id". So I guess I'd better test with that.

I put that code in the component that loads the dashboard. So if I want to give it a test, I'll fire up the Angular app and hit this URL: http://127.0.0.1:4200/dashboard?id=36

Then I'll look at the developer's console on the right-hand sidebar and see this:

36

And that makes sense because that's exactly the value I specified for id.

Note that the way you access a specific parameter is just like you'd access a single element in an array: with square braces. 

Unlike an array, though, you access the parameter by specifying its name ('id') instead of a numerical index.

That's how you can grab various parameters if you've got more than one appended to the route. Just use params['paramName'] for each one and you'll get the values.

Wrapping It Up

Now you know how to do it. You know how to grab query parameters in your components.

So take the code you see above and make it your own. Tweak it to suit your own business requirements.

Have fun!