Angular2 Routerlink: add query parameters

我是研究僧i 提交于 2019-12-03 06:12:03

问题


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>

?


回答1:


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');
}



回答2:


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>


来源:https://stackoverflow.com/questions/35226245/angular2-routerlink-add-query-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!