Angular Routing with Query Parameters
December 19, 2023
In this article, we will learn to create query parameters and retrieve them in Angular routing. I will cover following points here on this page.
Creating query parameters
1. with
queryParams
in routerLink
2. with
queryParams
in Router.navigate()
3. with absolute URL in
Router.navigateByUrl()
Retrieving query parameters
1. using
withComponentInputBinding
2. using
ActivatedRoute.queryParamMap
In my example, I have created following routes.
export const routes: Routes = [ { path: 'userdetail', component: UserDetailsComponent }, { path: 'companydetail', component: CompanyDetailsComponent }, ];
UserDetailsComponent
will execute.
For the path /companydetail, the component
CompanyDetailsComponent
will execute.
Now we will learn to create and retrieve query parameters for above path in detail.
Contents
1. Using queryParams with routerLink
routerLink
Directive makes an element a link to navigate a route. Navigation opens routed components in <router-outlet>
.
queryParams
is a property of routerLink
and is used to pass query parameters. Using queryParams
we can pass one or more query parameters.
Find the code snippet to use
queryParams
.
<nav> <ul> <li> <a routerLink="/userdetail" [queryParams]="{uname:'Mohan', age: 30, city:'Varanasi'}">User Details</a> </li> <li> <a routerLink="/companydetail" [queryParams]="{compname:'XYZ', compsize: 100}">Company Details</a> </li> </ul> </nav> <router-outlet></router-outlet>
/userdetail?uname=Mohan&age=30&city=Varanasi
/companydetail?compname=XYZ&compsize=100
queryParamsHandling :
queryParamsHandling
handles query parameters in a router link. It can have three values.
"merge" : Merge new parameters with current parameters.
"preserve" : Preserve current parameters.
"" : Default behaviour. Replace current parameters with new parameters.
Find the code to use
queryParamsHandling
with "merge" value.
<a routerLink="/userdetail" [queryParams]="{uname:'Mohan', age: 30, city:'Varanasi'}" queryParamsHandling="merge"> User Details </a>
2. Using queryParams with Router.navigate()
1.navigate()
is a method of Router
class. The parameters of navigate()
method is commands and navigation extras.
2. commands is an array of URL fragments with which the target URL is constructed.
3. extras is a
NavigationExtras
that has properties such as queryParams, fragment, relativeTo, queryParamsHandling, preserveFragment etc.
Find the code to pass query parameters using queryParams in
navigate()
method.
constructor(private route: ActivatedRoute, private router: Router) {} getUserDetails() { this.router.navigate(['userdetail'], { queryParams: {uname:'Sohan', age: 35, city:'Ayodhya'}, relativeTo: this.route }); } getCompanyDetails() { this.router.navigate(['companydetail'], { queryParams: {compname:'ABC', compsize: 150}, relativeTo: this.route }); }
queryParamsHandling
with Router.navigate()
as following.
this.router.navigate(['userdetail'], { queryParams: {uname:'Sohan', age: 35, city:'Ayodhya'}, relativeTo: this.route, queryParamsHandling: "merge" });
3. Using absolute URL with Router.navigateByUrl()
Router.navigateByUrl()
navigates to a view using an absolute route path. It accepts the values as given below.
navigateByUrl(url, extras)
UrlTree
.
extras is
NavigationBehaviorOptions
that modifies the Router
navigation strategy. Its properties are onSameUrlNavigation, skipLocationChange, replaceUrl, state. The extras is optional and default value is {skipLocationChange: false}
.
Find the example.
this.router .navigateByUrl("/userdetail?uname=Krishn&age=40&city=Dwarika");
4. Retrieving with withComponentInputBinding
Step-1: UsewithComponentInputBinding
with provideRouter
.
The
withComponentInputBinding
function enables binding information from the Router
state directly to the inputs of the component in Route
configurations.
bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withComponentInputBinding()) ] } );
RouterModule.forRoot
, we can pass bindToComponentInputs as true to enable binding information from the Router
state to the inputs of the component.
Step-2: Create
@Input()
properties with the same name or alias as key of query parameters.
a. In the URL,
/userdetail?uname=Mohan&age=30&city=Varanasi
In the component, we need to create
@Input()
properties as following.
@Input() uname: string; @Input() age: number; @Input() city: string;
@Component({ standalone: true, imports: [], template: 'User Detail Component' }) export class UserDetailsComponent implements OnInit { @Input() uname!: string; @Input() age!: number; @Input() city!: string; ngOnInit() { console.log("uname: " + this.uname); console.log("age: " + this.age); console.log("city: " + this.city); } }
uname: Mohan age: 30 city: Varanasi
/companydetail?compname=XYZ&compsize=100
@Component({ standalone: true, imports: [], template: 'Company Detail Component' }) export class CompanyDetailsComponent { @Input() compname!: string; @Input() compsize!: number; ngOnInit() { console.log("compname: " + this.compname); console.log("compsize: " + this.compsize); } }
compname: XYZ compsize: 100
5. Retrieving with ActivatedRoute.queryParamMap
To retrieve query parameters, usequeryParamMap
properties of ActivatedRoute
class. queryParamMap
is an Observable
that contains a map of the query parameters available to all routes.
constructor(private route: ActivatedRoute){} ngOnInit() { const userDetail$= this.route.queryParamMap.pipe( switchMap(params => { const uname = String(params.get('uname')); const age = Number(params.get('age')); const city = String(params.get('city')); console.log("uname: " + uname); console.log("age: ", age); console.log("city: ", city); return of("done"); }) ); userDetail$.subscribe(val=> console.log(val)); }