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.
ActivatedRoute
ActivatedRouteSnapshot
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.
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.
1ng 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
1import { NgModule } from '@angular/core';
2import { Routes, RouterModule } from '@angular/router';
3import { FirstComponent } from './first/first.component';
4
5const routes: Routes = [
6 {
7 path: 'first/:parameter',
8 component: FirstComponent,
9
10 },
11 {
12 path: "",
13 redirectTo: '/first/1',
14 pathMatch: 'full'
15 }
16];
17
18@NgModule({
19 imports: [RouterModule.forRoot(routes)],
20 exports: [RouterModule]
21})
22export 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
.
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.
To extract the parameter, we need to subscribe to the params
variable of the ActivatedRoute
. The following snippet shows this subscription.
first.component.ts
1import { Component, OnInit } from '@angular/core';
2import { Router, ActivatedRoute, ActivatedRouteSnapshot } from '@angular/router';
3
4@Component({
5 selector: 'app-first',
6 templateURL: './first.component.html',
7 styleURLs: ['./first.component.scss']
8})
9export class FirstComponent implements OnInit {
10
11 public parameterValue: string;
12
13 constructor(
14 private _router: Router,
15 private _activatedRoute: ActivatedRoute
16 ) { }
17
18 ngOnInit() {
19 this._activatedRoute.params.subscribe(parameter => {
20 this.parameterValue = parameter.parameter
21 this._router.navigate(['first/4'])
22 this.parameterValue = parameter.parameter
23 })
24
25 }
26}
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>
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
.
first.component.ts
1import { Component, OnInit } from '@angular/core';
2import { Router, ActivatedRoute, ActivatedRouteSnapshot } from '@angular/router';
3
4@Component({
5 selector: 'app-first',
6 templateURL: './first.component.html',
7 styleURLs: ['./first.component.scss']
8})
9export class FirstComponent implements OnInit {
10
11 public parameterValue: string;
12
13 constructor(
14 private _router: Router,
15 private _activatedRoute: ActivatedRoute
16 ) { }
17
18 ngOnInit() {
19
20 this.parameterValue = this._activatedRoute.snapshot.params.parameter
21 this._router.navigate(['first/4'])
22 this.parameterValue = this._activatedRoute.snapshot.params.parameter
23
24 }
25}
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.
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.