In angular 2 how to preserve query params and add additional query params to route

user7405505 picture user7405505 · Jan 18, 2017 · Viewed 13.4k times · Source

For example I am on route /cars?type=coupe and I want to navigate to the same endpoint with additional query params (but keeping existing one). I am trying something like this

<a [routerLink]="['/cars']" [queryParams]="{model: 'renault'}" preserveQueryParams>Click</a>

The initial query params are preserved (type=cars) but added ones (model=renault) are ignored. Is this expected/correct behavior or is some kind of bug? Looks like preserveQueryParams has priority over queryParams? Is there any other smooth solution?

Answer

DarkNeuron picture DarkNeuron · Nov 18, 2017

In Angular 4+, preserveQueryParams have been deprecated in favor of queryParamsHandling. The options are either 'merge' or 'preserve'.

In-code example (used in NavigationExtras):

this.router.navigate(['somewhere'], { queryParamsHandling: "preserve" });

In-template example:

<a [routerLink]="['somewhere']" queryParamsHandling="merge">