Angular Js

How to use Query Parameters in Angular?

How to use Query Parameters in Angular?

How to use Query Parameters in Angular?

This Article helps you to Understand, What are Query Parameters  and How to use Query Parameters in Angular?


Query parameters in Angular allow for passing optional parameters across any route in the application. Query parameters are different from regular route parameters, which are only available on one route and are not optional (e.g., /product/:id).


Declare Routes

{ path: "servers", component: ServersComponent },
{ path: "servers/:id", component: ServerComponent },
{ path: "servers/:id/edit", component: EditServerComponent }





Add Query Parameters from Service Listing Component

1. Add in template

<a
  [routerLink]="['/servers', server.id, 'edit']"
  [queryParams]="{ allowEdit: server.id === 3 ? '1' : '0' }"
  href="#"
  class="list-group-item"
  *ngFor="let server of servers"
>
  {{ server.name }}
</a>



2. Add  Query Parameters to the route programmatically
If you are navigating to the route imperatively using Router.navigate, you will pass in query parameters with queryParams.]
onLoadServer(id: number) {
  // complex calculation
  this.router.navigate(["/servers", id, "edit"], {
    queryParams: { allowEdit: "1" }
  });
}






Reading / Fetch Query Parameters

1. Using Observable
The ActivatedRoute class has a queryParams property that returns an observable of the query parameters that are available in the current URL.

import { ActivatedRoute, Params, Router } from "@angular/router";
@Component({
  selector: "app-edit-server",
  templateUrl: "./edit-server.component.html",
  styleUrls: ["./edit-server.component.css"]
})

allowEdit = false;

ngOnInit() {

  // this observable will allow you to react to change query string or fragment
  // there is no need to unsubscribe, angular will do this for us
  this.route.queryParams.subscribe();

  this.route.queryParams.subscribe((queryParams: Params) => {
    this.allowEdit = queryParams["allowEdit"] === "1" ? true : false;
  });

}



<h4 *ngIf="!allowEdit">You're not allowed to edit!</h4>
<div *ngIf="allowEdit">
  <div class="form-group">
    <label for="name">Server Name</label>
    <input
      type="text"
      id="name"
      class="form-control"
      [(ngModel)]="serverName"
    />
  </div>
  <div class="form-group">
    <label for="status">Server Status</label>
    <select id="status" class="form-control" [(ngModel)]="serverStatus">
      <option value="online">Online</option>
      <option value="offline">Offline</option>
    </select>
  </div>
  <button class="btn btn-primary" (click)="onUpdateServer()">
    Update Server
  </button>
</div>





2. Using Snapshot

console.log(this.route.snapshot.queryParams);


Drawback of snapshot: this only run / updated at the time component is created. so if there is chance to change query parameter or fragment, we currently on - this won't be reactive  at time. .


3.Using QueryParamMap

There’s also queryParamMap, which returns an observable with a paramMap object.
Given the following route URL: http://localhost:4200/products?order=popular&filter=new

this.route.queryParamMap
  .subscribe((params) => {
    this.orderObj = { ...params.keys, ...params };
  }
);


the resulting shape of the data in orderObj:

{
  "0": "order",
  "1": "filter",
  "params": {
    "order": "popular",
    "filter": "new"
  }
}




..



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