Angular Js

How Route Parameters Works in Angular?

How Route Parameters Works in Angular?

How Route Parameters Works in Angular?

This Article helps you to Understand, How Route Parameters Works in Angular?


Route parameters are the parameters that are sent with a URL.

Declaring Route Parameters
A route parameter for the ID of the product would be required for the component's route that displays the details for a given product.

const appRoutes: Routes = [
  { path: '', redirectTo: 'product-list', pathMatch: 'full' },
  { path: 'product-list', component: ProductList },
  { path: 'product-details/:id', component: ProductDetails }
];

id is a parameter that is placed in the product-details route's path.


Linking to Routes with Parameters
Here in ProductList component we are displaying a list of products. Each product would have a link to the product-details component through product id

<a *ngFor="let product of products"
  [routerLink]="['/product-details', product.id]">
  {{ product.name }}
</a>


Here routerLink directive passes an array which specifies the path and the route parameter.


Alternately, we could Programmatically navigate to the route

goToProductDetails(id) {
  this.router.navigate(['/product-details', id]);
}





Reading Route Parameters
The parameter must be read in the ProductDetails component before the product is loaded using the parameter's ID.
The ActivatedRoute service provides a params Observable which we can subscribe to to get the route parameters. The ActivatedRoute is a service, which keeps track of the currently activated route associated with the loaded Component.

Either the subscribe method or the snapshot method can be used to retrieve the parameters.


1. Using Snapshot Method


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

...
export class UserComponent implements OnInit {
  product: { id: number; name: string };

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.product = {
      id: this.route.snapshot.paramMap.get("id");
      name: ""
    };
  }
}


LETS CREATE A LINK
<div class="col-xs-12 col-sm-4">
  <div class="list-group">
    <a [routerLink]="['/product-details', 10]">
      Load Detail
    </a>
  </div>
</div>


Problem with Snapshot Option
When you only need the initial value, choose the Snapshot option. lets run the url directly in browser: http://localhost:4200/product-details/1

Now from inside product detail lets reopen the page by clicking load detail link
we see that on  clicking this link only url is updated, information on page is not updated.

Reason
It is the default behavior of Angular. It will update both url and content only when we are coming on users component from some other component. Since we first open user component directly using url and then click this link i.e. from same user component. it is just updating the url not content. as angular already render the user component before. Angular doesn't re-instantiate this component, it assumes, why why we re-render the component we already on to prevent performance issues.

Solution
-- its fine to use snapshot for the first initialization
-- but to be able to react on subsequent changes, we used some other approach i.e. params, observables



2. Using Observable

this.route.paramMap.subscribe(params => {
      this.id = params.get('id');
});


 
Why use observable
We usually retrieve the value of the parameter in the ngOninit life cycle hook, when the component initialised.

When the user navigates to the component again, the Angular does not create the new component but reuses the existing instance. The component's ngOnInit method is not invoked again in such cases. Consequently, you need a method of obtaining the parameter's value.

You can get the most recent parameter value and update the component by subscribing to the observable paramMap property. So, use this option if you expect the value of the parameter to change over time.




An Older Alternative: Params Array

The Older version of ActivatedRoute class has a Params array which is an array of the parameter values, indexed by name. You can still use it but It is now deprecated and is replaced by the ParamMap.


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

@Component({
  selector: 'product-details',
  template: `
    <div>
      Showing product details for product: {{id}}
    </div>
  `,
})

export class LoanDetails implements OnInit, OnDestroy {
  id: number;
  private sub: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.id = +params['id']; // (+) converts string 'id' to a number
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}


.



Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram