Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Routerlink: add query parameters

How can I add query parameters to routerLink?

@RouteConfig {    {path: '/search',   name: 'Search', component: SearchCmp} }   

Let' say I want to route to /search?q=asdf,

<a [routerLink]= " [ '/Search' , {q= 'asdf'}] ">Link 1</a> 

this resolves to /search .

Is there a way to add query parameters without using:

this.router.navigate( ['Search', { q: 'asdf'}]); 

or

<a href="/search?a=asdf"> Link 2 </a> 

?

like image 457
tisie Avatar asked Feb 05 '16 14:02

tisie


People also ask

How do I get query parameters in Angular 13?

Use queryParamMap to access query parameters. Another way to access query paramters in Angular is to use queryParamMap property of ActivatedRoute class, which returns an observable with a paramMap object.

What is difference between routerLink and routerLink?

What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.


2 Answers

If u need something as /search?q=asdf than you can simply use:

@RouteConfig {    {path: '/search',   name: 'Search', component: SearchCmp} }  //And to generate router Links use:  <a [routerLink]="['/Search']" [queryParams]="{q:'asdf'}"></a> 

This will generate the href tag as <a href="/search" but on clicking the anchor tag will lead you to url /search?q=asdf. [queryParams] will let you add the query params with "?", otherwise they will be appended by ";". You can get this parameter in your SearchCmp using:

constructor(private _routeParams: RouteParams) {    var queryParam = this._routeParams.get('q'); } 
like image 109
Saurabh Maurya Avatar answered Oct 18 '22 11:10

Saurabh Maurya


OP (Original Poster) asked how to add query parameters via router link, not a router parameters as @SaUrAbH MaUrYa answered.

To add query parameters you need to use [queryParams] binding:

<a [routerLink]="['/users']" [queryParams]="{ page: 1 }">next page</a> 
like image 34
pleerock Avatar answered Oct 18 '22 11:10

pleerock