How to pass query parameters with a routerLink

AngularAngular2 Routing

Angular Problem Overview


I want to pass a query parameter prop=xxx.

This didn't work

<a [routerLink]="['/somepath', {queryParams: {prop: 'xxx'}}]">
  Somewhere
</a>

Angular Solutions


Solution 1 - Angular

queryParams

queryParams is another input of routerLink where they can be passed like

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>

fragment

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>

routerLinkActiveOptions

To also get routes active class set on parent routes:

[routerLinkActiveOptions]="{ exact: false }"

To pass query parameters to this.router.navigate(...) use

let navigationExtras: NavigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

See also https://angular.io/guide/router#query-parameters-and-fragments

Solution 2 - Angular

<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/   \______________/\_________/ \_________/ \__/
 |           |            |            |        |
scheme    authority      path        query   fragment

For more info - https://angular.io/guide/router#query-parameters-and-fragments

Solution 3 - Angular

For those who want to pass dynamic querystring params, this worked for me:

assume you have component model

x = {name:'xyz'}

html:

<a [routerLink]="['../']" [queryParams]="{prop: x.name}">Somewhere</a>

this will generate link:

../?prop=xyz

Solution 4 - Angular

You can check out this as well.

 <router-link
 
:to="{name:'router-name', params: { id:param1}, query:{link:query1}}"

>
 link name

 </router-link
>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionG&#252;nter Z&#246;chbauerView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularVivek KumarView Answer on Stackoverflow
Solution 3 - AngularBraveNewMathView Answer on Stackoverflow
Solution 4 - AngularMuyingo StevenView Answer on Stackoverflow