Angular 10|9|8 Get URL or Set URL Parameters using Router and ActivatedRoute

Parameters passed in the URL can be easily accessed in Angular 10, 9, 8, 7, 6, 5, and 4 versions by using the ActivatedRoute class in @angular/router module.

Small portions of information can be easily passed via URLs from one component to the other which is not sensitive and can be shared publically.

It can be an ID of a record that can be fetched on other details component to fetch and display information related to that ID.

Parameters can be passed and get in 3 ways in an Angular application. We’ll discuss them all one by one with examples. Also, we’ll discuss how to change url param without reload using hash parameters.

Method 1: Passing URL parameters using Slash Separator

Parameters are passed inside the URL separated by slashes. These need to be defined in the Routes definition under path property:

For examples, we need to pass the parameter for ID and Color of the product to another page in this form:

www.example.com/product/1534/red

Here 1534 is and productid, so we need to define the Routes definition like this:

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { ProductDetailsComponent } from './product-details/product-details.component';

const routes: Routes = [
  {
      path: '',
      component: HomeComponent
  },
  {
    path: 'product/:productid/:color',
    component: ProductDetailsComponent
  }
 ];

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

 

Read Parameter in the Component

To read the production parameter passed in the URL we’ll import the ActivatedRoute class from @angular/router

// product-details.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-product-details',
  templateUrl: './product-details.component.html',
  styleUrls: ['./product-details.component.scss']
})
export class ProductDetailsComponent implements OnInit {

  constructor(
    private activatedRoute: ActivatedRoute
  ) { }

  ngOnInit() {

	
    let productid = this.activatedRoute.snapshot.params.productid;
    console.log(productid);// OUTPUT 1534
    let color = this.activatedRoute.snapshot.params.color;
    console.log(color);// OUTPUT red

    //Subscription Method
    this.activatedRoute.paramMap.subscribe(params => {
      productid = params.get('productid');
      console.log(productid);// OUTPUT 1534
      color = params.get('color');
      console.log(color);// OUTPUT red
    });
	
	
  }
}

Above we have used two ways to access URL parameters, first is using a snapshot and second is a subscription to the promise returned by paramMap() method.

 

Check if URL parameter exists in Angular Application

We can also check if the URL parameter exists or not. If we look at the above example the snapshot method will return null if no production or color parameter is found

let productid = this.activatedRoute.snapshot.params.productid; 
    console.log(productid);// OUTPUT null 

    if(productid === null){
      console.log('productid parameter not found');  
    }

On the other hand, the subscription method returns undefined if no parameter is found.

This will also work for both cases just add this:

if(productid){
      console.log('productid parameter Found');  
    }else{
      console.log('productid parameter Not Found');
    }

As null and undefined both will return false.

Method 2: Passing URL Parameters using question mark ampersand

Instead of passing the parameters separated by slashes(/), we can also pass in the tradition ways separated by ?;& characters as shown below:

www.example.com/product?productid=1534&color=red

 

Read Parameter in the Component

If Parameters are passed in this form, then we can read them subscribing to the queryParams observable as shown below:

import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-product-details',
  templateUrl: './product-details.component.html',
  styleUrls: ['./product-details.component.scss']
})
export class ProductDetailsComponent implements OnInit {

  constructor(
    private activatedRoute: ActivatedRoute
  ) { }

  ngOnInit() {

    this.activatedRoute.queryParams.subscribe(params => {
      let productid = params['productid'];
      let color = params['color'];
      
      console.log(productid);// OUTPUT 1534
      console.log(color);// OUTPUT red
    });

	
  }

}

 

Method 3: Passing the Hash # Parameter in URL

Sometimes we also pass # Hash fragment parameters in the URL as it does not change the pages. It can be passed in the following way

www.example.com/product#?productid=1543&color=red

 

Read Parameter in the Component

We can also pass URL parameters in the Hash format. The advantage is that we can change URL parameters in the Angular application without reloading.

The Hash fragment is also fetched by using the ActivatedRoute by subscribing to the fragment observable as shown below:

ngOnInit() {
	
    this.activatedRoute.fragment.subscribe((fragment: string) => {
      console.log(fragment);// OUTPUT ?productid=1543&color=red 
    })

  }

It works fine if you have passed the only ID like this www.example.com/product#1543 to return 1543.

But if you look above, we have a problem. It is printing complete fragment making it difficult to get each parameter value like id or color.

How to fetch Each Parameters value from Hash fragment passed?

We can use the URLSearchParams() method to read parameters out of fragment as shown below:

ngOnInit() {
	
    this.activatedRoute.fragment.subscribe((fragment: string) => {
	
      console.log(fragment);// OUTPUT ?productid=1543&color=red

      const urlParams = new URLSearchParams(fragment);
	  
      const productid = urlParams.get('productid')
      console.log(productid); // OUTPUT 1543
	  
      const color = urlParams.get('color')
      console.log(color); // OUTPUT red
	  
    })

  }

Easy. Right?

 

Conclusion

In this tutorial, we got to know different ways of passing the URL parameters in the Angular application and also how to read them individually in the component class.

We can pass any number of parameters in the URL and fetch them by using the snapshot or subscript to the methods available in the ActivatedRoute class.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments