Wednesday, January 8, 2020

Angular 9 Routing Tutorial

Angular 9 Route Parameter Example

Routes are fundamental building blocks of any application and we declare routes in the app-routing.module.ts file. Angular 9 Routing Tutorial Sending & Getting Routes Parameters 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 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-details template.
import { Component } from '@angular/core';
@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
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 9.
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-product-detail',
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css']
})
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.css']
})
export class ProductDetailComponent implements OnInit {
  product_id: string;
  constructor(private actRoute: ActivatedRoute) { }
  ngOnInit() {
    this.actRoute.paramMap.subscribe(params => {
      this.product_id = params.get('id');
    });
  }
 
}