Angular : Passing Optional (Query) Parameters to a route

In this tutorial, let us look at how to pass and access the Optional or query parameters in Angular. Query parameters allow you to pass optional parameters like page number to the component. In this tutorial, we look at how to pass the query parameters using the queryParams directive. We then look at how to retrieve the parameter in the component using the ActivatedRoute Service.

Applies to: Angular 2 to the latest edition of i.e. Angular 8. Angular 9, Angular 10

What are query parameters

Query parameters are optional parameters that you pass to a route. The query parameters are added to the end of the URL Separated by Question Mark

For Example

where page=2 is the query parameter

The above URL is an example of paginated product list, where URL indicates that second page of the Product list is to be loaded.

Difference between Query parameter and Route parameter

The route parameters are required and is used by Angular Router to determine the route. They are part of the route definition.

For Example, when we define the route as shown below, the id is the route parameter.

The above route matches the following URL The angular maps the values 1 & 2 to the id field

The Router will not navigate to the ProductDetailComponent route, if the id is not provided. It will navigate to ProductComponent instead. If the product route is not defined, then it will result in a error.

However, the query parameters are optional. The missing parameter does not stop angular from navigating to the route. The query parameters are added to the end of the URL Separated by Question Mark

Route Parameters or Query Parameters?

  • Use route parameter when the value is required
  • Use query parameter, when the value is optional.

How to use Query Parameters

The Query parameters are not part of the route. Hence you do not define them in the routes array like route parameters. You can add them using the routerlink directive or via router.navigate method.

Passing Query Parameters

Use the queryParams directive to add the query parameter. Use this directive along with the routerlink directive as shown below

The router will construct the URL as /product?pageNum=2

You can pass more than one Query Parameter as shown below

The router will construct the URL as /product?val1=2&val2=10

You can also navigate programmatically using the navigate method of the Router service as shown below

Reading Query Parameters

Reading the Query parameters is similar to reading the Router Parameter. There are two ways by which you can retrieve the query parameters.

Note that queryParams is deprecated. It is replaced by the queryParamMap.

Using queryParamsMap observable

The queryParamsMap is a Observable that contains a map of the query parameters available to the current route. We can use this to retrieve values from the query parameter. The
queryParamsMap is accessible via ActivatedRoute

Hence, we need to inject the ActivatedRoute in the constructor of the component/service,where we want to read the query parameter as shown below

You can subscribe to the queryParamMap of the ActivatedRoute, which returns the
observable of type ParamMap. We can then use the get method to read the query parameter as shown below.

Using snapshot.queryParamMap property

You can also read the value of the query parameter from queryParamMap using the snapshot property of the ActivatedRoute as shown below

Remember, the router populates the snapshot, when the component loads for the first time. Hence you will read only the initial value of the query parameter with the snapshot property. You will not be able to retrieve any subsequent changes to the query parameter.

queryParamsHandling

The query parameter is lost when the user navigates to another route.

For Example, if user navigates to the product page with route /product?pageNum=2 then he navigates to the product detail page, the angular removes the query parameter from the url. This is the default behaviour

You can change this behavior by configuring the queryParamsHandling strategy. This Configuration strategy determines how the angular router handles query parameters, when user navigates away from the current route. It has three options

queryParamsHandling : null

This is default option. The angular removes the query parameter from the URL, when navigating to the next..

queryParamsHandling : preserve

The Angular preserves or carry forwards the query parameter of the current route to next navigation. Any query parameters of the next route are discarded

queryParamsHandling : merge

The Angular merges the query parameters from the current route with that of next route before navigating to the next route.

Note that preserveQueryParams is DEPRECATED

Query Params Example

Let us build a small application to demonstrate the use of Query parameters

Let us update the app that we have built in the Passing Parameters to Route tutorial. You can download the code from gitHub. From the folder “Parameters” and the Final code at “QueryParameters”

AppComponent

app.component.ts

app.component.html

We have defined the pageNum variable in the component. An input box for the pageNum is provided, so that the user can change the page no.

The AppComponent has the navigation Menu. It contains the link to the product page. The link is created using the routerlink directive. The routerlink directive contains the queryParams directive, where we pass the pageNum to "pageNum" variable.

The Angular will construct the URL as /product?pageNum=2

Product Component

The ProductComponent does not display any products. But it displays the query parameters received

product.component.ts

product.component.html

First, we have injected both ActivatedRoute and Router Service in the constructor of the ProductComponent

Next, in the ngOnInit lifecycle hook, we use the Activatedroute.snapshot method to retrieve the pageNum and update the snapshotPageNo variable.

We also subscribe to the queryParams property. We are updating our local variable pageNo with page number obtained from the Queryparams

In our template, we display both snapshotPageNo pageNo variable.

We also have nextPage method.

Here we are using the router.navigate method to navigate to the next page. This actually does not change route as we are already in the page. The angular router does not re create the component, but since we have subscribed to the Query parameters, we will be notified of the change in page Number. The pageNum variable is updated to the new value, while the snapshotPageNo does not change

Other Components

app.module.ts

app.routes.ts

home.component.ts

contact.component.ts

Testing the Application

Run the application, enter the page Number and click on the Product Link.

2 thoughts on “Angular : Passing Optional (Query) Parameters to a route”

  1. your next (“Navigation Between Routes”) is not working its showing 404 error. hence you write a very nice, good and valuable blog. i just read only angular2 and you explain in very good manner with good coding style. keep it up and also enable the page as i mentioned earlier. Please available on you tube also with live example. if you have time to get in touch with your user try to come on skype that will more valuable to your user to solve there query.

    Once again lots of thanks to write this blog.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top