Sending & Getting Routes Parameters in Angular 16 App

Last Updated on by in Angular
In this Angular 16 Routing tutorial, we will learn how to set parameters to routes along with that we will also look at how to access or get parameters from the route using ActivatedRoute’s snapshot and paramMap method.In the first step, we will learn how to create routes and set parameters in the routes with the help of Angular’s [routerLink]="[..]" directive.

Then, In the second step, we will understand how to access the route params. Angular offers two ways to access the route parameters, you can use ActivatedRoute service to get the route params with snapshot or paramMap method.

We will check both the ways to get the route parameters.

In almost every applications, we navigate from one page to another page and this can be done with accessing URL or paths.

We will create the products page and define the route for it and pass the parameters to the url.

And get those parameters in product-detail page. So our basic app will have product and product-details components and their associated paths.

Check out our detailed tutorial on Angular Routing & Navigation.

Setting Up Angular Project

Run the below command to generate a brand new Angular project using Angular CLI.

ng new angular-demo

Head over to the Angular form project.

cd angular-demo

Angular 16 Route Parameter Example

First, execute given command to generate components:

ng g c products

ng g c product-detail

Routes are fundamental building blocks of any application and we declare routes in the app-routing.module.ts file. Routes permit users to navigate from one page to another page.

The path: '' parameter relates to the url where the user will land when entered in the browser’s address bar.

Here, component relates to the component whose data to be shown to the user for the specified path.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { ProductsComponent } from './products/products.component';
import { ProductDetailComponent } from './product-detail/product-detail.component';

const routes: Routes = [
  { path: 'products', component: ProductsComponent },
  { path: 'product-detail/:id', component: ProductDetailComponent },
];

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

export class AppRoutingModule { }

Here are the routes we defined in Angular.

  • /products
  • /product-detail/:id

Defining Route with Parameter

We defined the product-detail route in the AppRoutingModule, the /product-detail/:id, here we pass the parameter in the form of product id. This route will redirect to the associated product page.

{ path: 'product-detail/:id', component: ProductDetailComponent }

Here, we passed the one parameter however you can pass multiple parameters in a single route. That, totally depends on the route structure you opt for.

{ path: 'product/:id/:color/:category/:size', component: ProductDetailComponent }

In the above example, you can pass product id, color, category or size parameter in the Angular route URL. But in this demo we will stick to the one parameter.

Configure Navigation & Passing Parameters to Route

To visit the products page, inject the routerLink="/products" directive in the anchor tag. To enable the active class in Angular 10/9, use the routerLinkActive="" directive along with the active CSS class.

<a routerLinkActive="active" routerLink="/products">Products</a>

Before, we pass the parameter we need to define the static product’s data in the product components.

import { Component } from '@angular/core';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.scss']
})

export class ProductsComponent {

  Products = [
    {
      id: "ABC8441189035",
      name: "Tshirt",
      description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
    },
    {
      id: "DEF6510463347",
      name: "Shoes",
      description: "Proin ac metus in diam porttitor viverra eu sit amet ligula."
    },
    {
      id: "GHI0831819467",
      name: "Handbags",
      description: "Duis sodales dui vitae urna varius, at ullamcorper purus tempor."
    }
  ]

}

Here is how you set the parameter in the route.

<div *ngFor="let products of Products">
    <a [routerLink]="['/product-detail/', products.id]">Product Detail</a>
</div>

We are saving product data in the Products array and using the *ngFor directive to loop over the data and getting the product’s id and passing to the routerLink directive.

ActivatedRoute Snapshot

In this step, we will get the route parameters using the snapshot.param method. The snapshot method can be accessed with the help of ActivatedRoute service in Angular.

The ActivatedRoute service helps you monitor the currently activated route associated with the presently initiated component.

For using the Activated route, we need to Import as given below.

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

Next, define it inside the constructor.

constructor(private actRoute: ActivatedRoute) { }

Here is a basic example of retrieving route parameter using ActivatedRoute service in Angular.

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

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.scss'],
})

export class ProductDetailComponent {
  product_id: string;

  constructor(private actRoute: ActivatedRoute) {
    this.product_id = this.actRoute.snapshot.params['id'];
  }
}

Display the route parameter in the HTML template.

<h6>Product Id: {{product_id}}</h6>

ActivatedRoute – Subscribe paramMap

Another method of getting the route parameter is to use the paramMap object, and it can be located with the help of ActivatedRoute service.

The paramMap method is easy to use and provides two methods to get the value of the parameters. Those methods are get and getAll.

Go for has method if you want to make sure if any particular parameter exists in the route with paramMap.

Subscribe the paramMap method, and It is easy to use and helpful in getting the route parameters dynamically.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.scss'],
})

export class ProductDetailComponent implements OnInit {
  product_id!: string;

  constructor(private actRoute: ActivatedRoute) {}

  ngOnInit() {
    this.actRoute.paramMap.subscribe((params) => {
      this.product_id = params.get('id')!;
    });
  }
}

Conclusion

Finally, we have understood how to pass and set parameters in Angular routes.

I hope you liked this tutorial, please share this tutorial with others.