Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Accessing Route Parameters with ActivatedRoute vs. AcitivatedRouteSnapshot

Mar 3, 2020 • 7 Minute Read

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.

      ng g c First --skipTests=true
    

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

      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 { }
    

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 **

      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
    })

  }
}
    

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 **

      <h1>{{parameterValue}}</h1>
    

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 **

      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

  }
}
    

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.

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author