Author avatar

Gaurav Singhal

Accessing Route Parameters with ActivatedRoute vs. AcitivatedRouteSnapshot

Gaurav Singhal

  • Mar 3, 2020
  • 7 Min read
  • 10,866 Views
  • Mar 3, 2020
  • 7 Min read
  • 10,866 Views
Languages Frameworks and Tools
Angular

Introduction

We often need to get a route parameter so we can make a component dynamic based on that parameter. In this guide, we'll learn how to extract data or a parameter from a URL, including several different approaches.

What We'll Cover

  1. The need to get a parameter from a URL
  2. How to make a dynamic parameter in the route path
  3. How to extract a parameter from a URL
  4. How to extract a parameter using ActivatedRoute
  5. How to extract a parameter using ActivatedRouteSnapshot

The Need to Get a Parameter from a URL

If you have defined your route paths in app-routing.module.ts, why would you need a dynamic path?

Suppose you have a list of students in a grid format, as in the below image.

As you can see, the grid-template has the name, standard, and division of the student, and if you need to see more data for the student, you can click on Read More.

After a user clicks on Read More, you display a view or edit page with data from a database. As you're building the page, you don't know the student id to hit the API (Application Program Interface) and provide the rest of the student data to the view or edit page.

You need to store the student id somewhere. But where?

You might be thinking that you can achieve this using observable. And you can. But it has some limitations. For example, Your data will be lost after the page is refreshed.

So it's best to send the student ID in route parameter and get that parameter in the ngOnInit() method, which is one of the life cycle hooks in Angular.

Now it's clear why and where to use a dynamic parameter in the route path. So let's go ahead and see how to make a dynamic parameter in the route path and what the different options are to extract that parameter in the component.

Make a Dynamic Parameter in the Route Path

To extract the parameter, you need to make the dynamic parameter in the route path so that you can extract the value of the parameter by parameter name.

Do'nt understand? Don't worry! I'll explain it through an example.

First, we're going to create a component.

1
ng g c First --skipTests=true
console

Now we need to configure app-routing.module.ts. We make a route path that has a dynamic parameter that will be displayed in the HTML.

app.routing.module.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FirstComponent } from './first/first.component';

const routes: Routes = [
  {
    path: 'first/:parameter',
    component: FirstComponent,
  
  },
  {
    path: "",
    redirectTo: '/first/1',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
ts

Now our app-routing.module.ts is ready with configuration and it's time to extract the value of the dynamic parameter and display it on the HTML page.

We'll extract the dynamic parameter in two ways: using ActivatedRoute and ActivatedRouteSnapshot.

Extract a Parameter from a URL

Now we'll extract the parameter in FirstComponent where we have configured the route /first/:parameter.

First, we need to make an instance of ActivatedRoute for both ActivatedRoute and ActivatedRouteSnapshot. We'll create an instance in the constructor of FirstComponent.

To see the difference between ActivatedRoute and ActivatedRouteSnapshot, we'll make another instance of Router to change the route runtime.

Extract a Parameter Using `ActivatedRoute`

To extract the parameter, we need to subscribe to the params variable of the ActivatedRoute. The following snippet shows this subscription.

first.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ActivatedRouteSnapshot } from '@angular/router';

@Component({
  selector: 'app-first',
  templateURL: './first.component.html',
  styleURLs: ['./first.component.scss']
})
export class FirstComponent implements OnInit {

  public parameterValue: string;

  constructor(
    private _router: Router,
    private _activatedRoute: ActivatedRoute
  ) { }

  ngOnInit() {
    this._activatedRoute.params.subscribe(parameter => {
      this.parameterValue = parameter.parameter
      this._router.navigate(['first/4'])
      this.parameterValue = parameter.parameter
    })

  }
}
ts

The above snippet shows that we have made an instance of Router and ActivatedRouter, as we discussed. In the ngOnInit() life cycle hook, we have to subscribe to the params variable of ActivatedRoute.

After getting the value of the parameter, we change the value of the route or navigae dynamically and store the value of the parameter in the parameterValue variable. It will display in the HTML of the FirstComponent.

first.component.html

1
<h1>{{parameterValue}}</h1>
html

Now It's time to run the code and see the output in the browser.

As you can see, we got the new value of the parameter that we changed at runtime. Our parameter value has changed from 1 to 4. This means it changed from the starting value to the new value.

Now let's extract the value using ActivatedRouteSnapshot.

Extract a Parameter Using `ActivatedRouteSnapshot`

first.component.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, ActivatedRouteSnapshot } from '@angular/router';

@Component({
  selector: 'app-first',
  templateURL: './first.component.html',
  styleURLs: ['./first.component.scss']
})
export class FirstComponent implements OnInit {

  public parameterValue: string;

  constructor(
    private _router: Router,
    private _activatedRoute: ActivatedRoute
  ) { }

  ngOnInit() {

    this.parameterValue = this._activatedRoute.snapshot.params.parameter
    this._router.navigate(['first/4'])
    this.parameterValue = this._activatedRoute.snapshot.params.parameter

  }
}
ts

In the above snippet, the snapshot variable of the ActivatedRoute is the instance of ActivateRouteSnapshot.

We are doing the same thing we did in ActivatedRoute. We are getting the value of the dynamic parameter of the route, storing the value of it in a variable named parameterValue, and displaying it in the HTML.

Now It's time to run the application with this configuration and look at the output.

As you can see, we got the same value in the parameterValue variable, but our route has changed from first/1 to first/4.

We didn't get the value of the changed parameter. That is the difference between ActivatedRoute and ActivatedRouteSnapshot. In ActivatedRouteSnapshot, our values in the component and route are not in sync.

Conclusion

Thank you for reading this guide. I hope you have enjoyed it. Now you have a clear idea about where to use ActivatedRoute and ActivatedRouteSnapshot. If you are interested in learning more about them, you can go here.

13