Hello guys, In my previous post you have learned about the basics of router and navigations in angular. In this post we will go through the important part of the router module i.e ActivatedRoute
Use of ActivatedRoute ?
It can be used to pass data from one component to another component using URL. like sending Id, status etc.
What is ActivatedRoute ?
ActivatedRoute contains the information related to the route which is associated with the component. It is an interface in angular.
Let’s see the example
In the very first step I am generating Product List component and Product Detail component.
Step 1 – Generate components
ng g c product-list ng g c product-detail
Step 2 – Set the routes in app-routing.module.ts
const routes: Routes = [ { path: 'list', component: ProductListComponent }, { path: 'detail/:id', component: ProductDetailComponent }, { path: '', redirectTo: '/list', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ];
To learn about how routing works follow this post.
Step 3 – Create a service using CLI to fetch a list of products.
ng g s product
Step 4 – Update the code of the service file like this.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ProductService { private products = [ { id: 1, name: 'Product A', description: 'This is product A' }, { id: 2, name: 'Product B', description: 'This is product B' }, { id: 3, name: 'Product C', description: 'This is product C' }, { id: 4, name: 'Product D', description: 'This is product D' }, { id: 5, name: 'Product E', description: 'This is product E' }, ]; constructor() { } getProductList() { return this.products; } getProductDetailById(id) { return this.products.filter((product) => { return (product.id == id) }) } }
Explanation:
In this step i have created a list of some dummy products with 3 attributes that is id, name and description of the product.
I have also created two methods. First method is simply returning the list of products and second method returning the specific product based on the product id.
Step 5 – Open product-list.component.ts file and inject the ProductService which was created in the previous steps.
import { Component, OnInit } from '@angular/core'; import { ProductService } from '../product.service'; @Component({ selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css'] }) export class ProductListComponent implements OnInit { public productList: any = []; constructor(private _productService: ProductService) { } ngOnInit() { this.productList = this._productService.getProductList(); } }
Step 6 – In this step we will generate the list of products using ngFor and set the routerLink to redirect the user on the product detail page.
Open product-list.component.html file and write this code.
<h1>List of Products</h1> <br /> <ul> <li *ngFor="let product of productList"> <a [routerLink]="['/detail',product.id]">{{product.name}}</a> </li> </ul>
Explanation:
Look at this code
[routerLink]="['/detail',product.id]"
In simple words we are just sending the user on the product detail page with the product id so we can fetch the details of the product on the basis of id.
Remember, in step 2 we have used the id fragment with the product detail route
{ path: 'detail/:id', component: ProductDetailComponent }
Step 7 – In this step we will use the ActivatedRoute to get the id from the url and fetch details of the product using that id.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { ProductService } from '../product.service'; @Component({ selector: 'app-product-detail', templateUrl: './product-detail.component.html', styleUrls: ['./product-detail.component.css'] }) export class ProductDetailComponent implements OnInit { constructor( private _activatedRoute: ActivatedRoute, private _productService: ProductService ) { } public productId: number; public productDetail: any; ngOnInit() { this._activatedRoute.params.forEach((params: Params) => { this.productId = params['id']; // get the id from url let product = this._productService.getProductDetailById(this.productId); // pass the id to the service. if (product.length > 0) { this.productDetail = product[0]; } }); } }
Step 8 – Show product information to the user.
<h1>Product Detail Page</h1> <p>Produt ID - {{productDetail.id}}</p> <p>Produt Name - {{productDetail.name}}</p> <p>Produt Description - {{productDetail.description}}</p> <a routerLink="/list">Back to List</a>
Check the complete code in github
Thanks for reading this post. Please upvote this post if you like it and also share it with your friends who are learning angular.