Query Parameters
Written By: Avinash Malhotra
Updated on
Angular Query Parameter are required to handle dynamic query parameters. Query Parameters are mostly seen in search results, like google or e commerce searches.
Query parameters are also use full in pagination.
https://www.google.com/search?q=angular
Query parameter example
To use query parameter in angular, we need ActivatedRoute, same like dynamic routes. Also we need RouterLink.
app.routes.ts
<!--app.routes.ts-->
import { Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { ProductComponent } from './product/product.component';
import { SearchComponent } from './search/search.component';
import { ErrorComponent } from './error/error.component';
import { HomeComponent } from './home/home.component';
export const routes: Routes = [
{ path: '', component:HomeComponent, pathMatch:'full'},
{ path: 'login', component:LoginComponent},
{ path:'product', component:ProductComponent},
{ path: 'search/', component:SearchComponent},
{ path:'**', component:ErrorComponent},
];
search.component.ts
Import ActivatedRoute in search.component.ts. In ngOnInit Life Cycle Hook
, write the following code. I am using Observable with live code example
<!--search.component.ts-->
import { Component } from '@angular/core';
import { ActivatedRoute, RouterLink } from '@angular/router';
@Component({
selector: 'search-product',
standalone: true,
imports: [RouterLink],
templateUrl: './search.component.html',
styleUrl: './search.component.css'
})
export class SearchComponent {
searchItem:any;
constructor(private route:ActivatedRoute){};
ngOnInit(){
this.route.queryParams.subscribe((p)=>{
this.searchItem=p;
console.log(p);
});
}
}
search.component.html
Now add routerLink and queryParams in template as shown in example below.
<!--search.component.html-->
<p>search works!</p>
<a [routerLink]="['/search']" [queryParams]="{name:'swift', fuel:'petrol'}">Swift Petrol</a>
<a [routerLink]="['/search']" [queryParams]="{name:'brezza', fuel:'cng'}">Brezza CNG</a>
<a [routerLink]="['/search']" [queryParams]="{name:'fortuner', fuel:'diesel'}">Fortuner Diesel</a>
<p>Car is {{searchItem.name}} and fuel is {{searchItem.fuel}}</p>