How To Pass Parameters To The Route In Angular.
In this article, We will learn how to pass parameters (route parameters) or data to the Route in Angular. Let's start by looking at how to create a route that accepts the parameter. The routerLink directive is then used to pass the arguments to the route. Finally, we'll look at how to use the ActivatedRoute Service to get the parameters. Either the snapshot method or the subscribe method can be used to retrieve the parameters. We'll look at both of these approaches.
There are numerous instances in which parameters must be passed to the route. To navigate to the product detail view, for example, we must supply the product ID to the component so that it may retrieve and display it to the user.
Let's expand on the Routing & Navigation article's application by adding a product detail page that displays product details based on the Product ID given in the URL. This article's code may be found on Github under the folder parameters.
What are Route Parameters
The Route parameters are an important aspect of determining the route because they are dynamic.
Take, for example, the following path.
{ path: 'product', component: ProductComponent }
/product/1 /product/2
How to Pass parameters to Angular Route
Defining the Route
{ path: 'product/:id', component: ProductDetailComponent }
{ path: 'product/:id/:id1/:id2', component: ProductDetailComponent }
Defining the Navigation
<a [routerLink]="['/Product', ‘2’]">{{product.name}} </a>
<a [routerLink]="['/Product', product.productID]">{{product.name}} </a>
Retrieve the parameter in the component
ActviatedRoute
import { ActivatedRoute } from '@angular/router';
Then use dependency injection to inject it into the component.
constructor(private _Activatedroute:ActivatedRoute)
ParamMap
- Using Snapshot
- Using observable
Using Snapshot
this.id=this._Activatedroute.snapshot.paramMap.get("id");
Using Observable
this._Activatedroute.paramMap.subscribe(params => { this.id = params.get('id'); });
Why use observable
Passing Parameters to Route: Example
import { Component, OnInit } from '@angular/core'; import { ProductService } from './product.service'; import { Product } from './product'; @Component({ templateUrl: './product.component.html', }) export class ProductComponent { products:Product[]; constructor(private productService:ProductService){ } ngOnInit() { this.products=this.productService.getProducts(); } }
Add the following code under the product.component.html file:
<h1>Product List</h1> <div class='table-responsive'> <table class='table'> <thead> <tr> <th>ID</th> <th>Name</th> <th>Price</th> </tr> </thead> <tbody> <tr *ngFor="let product of products;"> <td>{{product.productID}}</td> <td><a [routerLink]="['/product',product.productID]">{{product.name}} </a> </td> <td>{{product.price}}</td> </tr> </tbody> </table> </div>
Add the following code under the product.service.ts file:
import { Observable } from 'rxjs'; import {Product} from './Product' export class ProductService{ public getProducts() { let products:Product[]; products=[ new Product(1,'Memory Card',500), new Product(2,'Pen Drive',750), new Product(3,'Power Bank',100) ] return products; } public getProduct(id) { let products:Product[]=this.getProducts(); return products.find(p => p.productID==id); } }
Add the following code under the product.ts file:
export class Product { constructor(productID:number, name: string , price:number) { this.productID=productID; this.name=name; this.price=price; } productID:number ; name: string ; price:number; }
We inserted product.productID as the second argument to the routerLink parameters array in product.component.html.
<a [routerLink]="['/product',product.productID]">{{product.name}} </a>
Product Details Component
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router,ActivatedRoute } from '@angular/router'; import { ProductService } from './product.service'; import { Product } from './product'; @Component({ templateUrl: './product-detail.component.html', }) export class ProductDetailComponent { product:Product; id; constructor(private _Activatedroute:ActivatedRoute, private _router:Router, private _productService:ProductService){ } /* Using snapshot */ // ngOnInit() { // //This still works but is deprecated // //this.id=this._Activatedroute.snapshot.params['id']; // this.id=this._Activatedroute.snapshot.paramMap.get("id"); // let products=this._productService.getProducts(); // this.product=products.find(p => p.productID==this.id); // } /* Using Subscribe */ sub; ngOnInit() { this.sub=this._Activatedroute.paramMap.subscribe(params => { console.log(params); this.id = params.get('id'); let products=this._productService.getProducts(); this.product=products.find(p => p.productID==this.id); }); // This params is deprecated //this.sub=this._Activatedroute.params.subscribe(params => { // this.id = params['id']; // let products=this._productService.getProducts(); // this.product=products.find(p => p.productID==this.id); // //}); } ngOnDestroy() { this.sub.unsubscribe(); } onBack(): void { this._router.navigate(['product']); } }
Add the following code under the product-detail.component.html file:
<h3>Product Details Page</h3> product : {{product.name}} price : {{ product.price}} <p> <a class='btn btn-default' (click)="onBack()">Back </a> </p>
We imported the router and ActivatedRoute from the angular router module into the ProductDetailComponent.
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Router,ActivatedRoute } from '@angular/router';
We inject the ActivatedRoute, Router, and ProductService services into the constructor.
constructor(private _Activatedroute:ActivatedRoute, private _router:Router, private _productService:ProductService){ }
Using snapshot
ngOnInit() { //This still works but is deprecated //this.id=this._Activatedroute.snapshot.params['id']; this.id=this._Activatedroute.snapshot.paramMap.get("id"); let products=this._productService.getProducts(); this.product=products.find(p => p.productID==this.id); }
Using Subscribe
ngOnInit() { this.sub=this._Activatedroute.paramMap.subscribe(params => { console.log(params); this.id = params.get('id'); let products=this._productService.getProducts(); this.product=products.find(p => p.productID==this.id); }); // This params is deprecated //this.sub=this._Activatedroute.params.subscribe(params => { // this.id = params['id']; // let products=this._productService.getProducts(); // this.product=products.find(p => p.productID==this.id); // //}); }
import { Routes } from '@angular/router'; import { HomeComponent} from './home.component' import { ContactComponent} from './contact.component' import { ProductComponent} from './product.component' import { ErrorComponent} from './error.component' import { ProductDetailComponent} from './product-detail.component' export const appRoutes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'contact', component: ContactComponent }, { path: 'product', component: ProductComponent }, { path: 'product/:id', component: ProductDetailComponent }, { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: '**', component: ErrorComponent } ];
The following route has been added to our routes array.
{ path: 'product/:id', component: ProductDetailComponent },
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Routing Module - Parameters Demo'; }
Add the following code under the app.component.html file:
<div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" [routerLink]="['/']"><strong> {{title}} </strong></a> </div> <ul class="nav navbar-nav"> <li><a [routerLink]="['home']">Home</a></li> <li><a [routerLink]="['product']">Product</a></li> <li><a [routerLink]="['contact']">Contact us</a></li> </ul> </div> </nav> <router-outlet></router-outlet> </div>
Now, put the following code under the contact.component.ts:
import {Component} from '@angular/core'; @Component({ template: `<h1>Contact Us</h1> <p>TekarticlesHub </p> ` }) export class ContactComponent { }
Add the following code under the home.component.ts file:
import {Component} from '@angular/core'; @Component({ template: `<h1>Welcome!</h1> <p>This is Home Component </p> ` }) export class HomeComponent { }
Update the error.component.ts file with the following code:
import {Component} from '@angular/core'; @Component({ template: `<h1>Page not found</h1> <p>This is a Error Page</p> ` }) export class ErrorComponent { }
Update the app.module.ts file using the following code:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { HomeComponent} from './home.component' import { ContactComponent} from './contact.component' import { ProductComponent} from './product.component' import { ErrorComponent} from './error.component' import { ProductDetailComponent} from './product-detail.component' import { ProductService } from './product.service'; import { appRoutes } from './app.routes'; @NgModule({ declarations: [ AppComponent,HomeComponent,ContactComponent,ProductComponent,ErrorComponent,ProductDetailComponent ], imports: [ BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(appRoutes) ], providers: [ProductService], bootstrap: [AppComponent] }) export class AppModule { }