What are route parameters?

We have unique identifiers that allow us to access a particular item in a list. We pass that unique identifier as a route parameter to our route and display the view of the details of the item associated with that particular identifier. These are the variables passed within the routes whose value depends on the chosen product or item. In the previous lesson, you were acquainted with the use of route parameters. Our goal in this lesson is to understand what that means and how can we use route parameters in our application.

Here, the common route is the user that is a constant route whereas :id is a placeholder for the variable route which is dependent on which product is chosen. We can have multiple variable routes too in the application. For example,

localhost:4200/user/:id/products/:num

Configuring the route parameter

{path: ‘user/:id’, component: UserDetails}

To activate the routes that have route parameters passed in, use the following syntax.

From the template

<a [routerLink] = “[‘/user’, user.id]”>{{user.userName}}</a>

<a [routerLink] = “[‘/user’, 0]”>Create User</a>

In the first line of code, the id of the user is passed, and this redirects the view to the user details with that id. However, if the id is passed as 0, it should redirect the view to create a new user since 0 is not associated with any user yet. Similarly,

From the Component, this.router.navigate([‘/user’, this.user.id])

This will navigate to the view of the user with this id and will appear in the browser as something like this.

The view displays the URL against the user with id 5. But as you see, we cannot really see the data, even though the URL appears to be correct. So, this happens because we have just configured the route parameters but are not actually reading them. To populate the view with the data contained in a particular routed-to component, we need to read the route parameters.

After configuring and using a basic example of route parameters, let’s now move on further to see how we can read parameters.

Reading route parameters

Till now, we have configured the routes and can see the change in the URL, but what about the data that is to be retrieved? To read the route parameters from the activated component, we use the ActivatedRoute service.

This service helps us read the route parameters and display the data corresponding to a particular route. To inject this service,

constructor( private activateRoute: ActivatedRoute)

After having injected the service, we use the snapshot option of this service that provides us with the initial state of this route. To access the route parameter, we use paramMap.get() method and pass in the placeholder for the route parameter as the argument.

const id = this.activateRoute.snapshot.paramMap.get(‘id’)

After receiving the initial value, we would want to change the view every time the value of the parameter changes. To subscribe to the change in the parameter value, the service provides this observable paramMap that will get notified every time there is some change in the router parameter value.

this.activateRoute.paramMap.subscribe(){
parameters => {     
const id =  parameters.get('id');
}}

Using the snapshot option of the ActivatedRoute service

To use the snapshot method, the first step that we need to perform is to import the service.

import {ActivatedRoute} from ‘@angular/router’;

Having imported the service, let’s inject it inside the constructor of the component. This is similar to what we saw earlier in this lesson.

constructor( private activateRoute: ActivatedRoute)

Now, since the snapshot option helps to get the initialized state of the route, we need to give a thought as to where exactly to place this statement which reads the data. 
Now that is when the lifecycle hook ngOnInit() comes into play.

ngOnInit(){ 
const id = this.activateRoute.snapshot.paramMap.get('id');  
this.getUser(id);}

In scenarios when we need to capture the data on any change that has taken place, we use the observable provided by the ActivatedService, i.e. paramMap

The paramMap observable will subscribe to the change that takes place in the value of the variable route parameter inside the constructor where we have injected the dependency of the ActivatedRoute service.

After importing the ActivatedRoute service from the angular/router and injecting the service inside the constructor, the paramMap observable will subscribe to the value of the change in the route parameter.

constructor (
private activateRoute: ActivatedRoute){
   this.activateRoute.paramMap.subscribe(
   parameters => {
      console.log(parameters.get(‘id’));
});
}

Now that we have seen the usage of both the snapshot and observable, we need to figure out when to use each.

Use snapshot when:

  • You want to read the route parameters only once
.
  • You want to keep the code simple, and you know there is no scope for changes.

Use Observable when:

  • The parameter is expected to change repeatedly.
  • You want to get notified of the changes in the route parameters and subscribe to that data.
  • After you have read the route parameters and are able to successfully view the data on the specific routes, the next bit to jump into is to see what the other optional parameters are.

Query and optional parameters

When we want to pass in some optional information to the route, we use optional parameters. Optional parameters make it easy to access the more complex information by having key-value pair naming technical in the route.

To define the optional parameters, we use the same routerLink array and pass them in using the key and value pairs.

<a [routerLink] = [‘/users’, {name: username, age: userAge}]> 

Now since each parameter has a unique key, they are easily identifiable and do not complicate the route configuration.

The resulting URL then looks like this:

https://localhost:4200/users;name=Manish;age=42

As we can see in the generated URL, it has these key-value pairs with unique identifiers for each of the optional parameters so no route collision issues will take place.

Reading the optional parameters

To read the optional parameters, we will import the ActivatedRoute service as earlier and inject it inside the constructor. Next, we will put the optional parameters in the routerLink array and then finally use it inside the constructor using the snapshot option to get the parameters through the code. We can see this using: console.log(this.activateRoute.snapshot.paramMap.get(‘name’));

Query parameters

Query parameters help in situations where you want to pass optional information to the component but also want to retain it after some operation has been performed on the component. Query parameters help to communicate across multiple routes, therefore retaining the data retrieved on a particular component view.

The syntax that query parameters follow is starting with a question mark and an ampersand as a separator.

https://localhost:4200/users/?nameby=this&age=some

To define the query parameters, we use the queryParams directive to bind to the information and it is not passed as a part of the routerLink array.

It basically looks like this:

<a [routerLink]= “/users”, user.id
      [queryParams] =“{…}”></a>

From the code,

this.router.navigate([‘/users’].{
        queryParams: {…}
);

Query parameters also contain key-value pairs like the optional parameters. Now when we navigate back from the current page, we want the data to be retained. To retain the data, we can use the queryParamsHandling directive to preserve the data that has been changed.

<a [routerLink]= “[‘/users’]”,    queryParamshandling=”preserve”></a>

This retains the URL in the browser, but we should not forget that we need to read the parameters.

Reading the query parameters

To read the query parameters, we will perform the same steps as earlier. Importing the ActivatedRoute service from the Angular route and injecting it inside the constructor. Inside the constructor, we will use the get method to read the query parameters like this:

console.log(this.activateRoute.snapshot.queryParamMap.get(‘’));

This will finally read the parameter and display the data as per the query parameters.

Get hands-on with 1000+ tech skills courses.