0

Is it possible to configure router links to simply add to the query string so that we can build a query string through a series of links?

Given the url:

http://localhost/app

And a link somewhere on the page similar to this:

<a [routerLink]="['.']" [queryParams]="{ foo: 1 }">link 1</a>

Would link to:

http://localhost/app?foo=1

Given a second link:

<a [routerLink]="['.']" [queryParams]="{ bar: 1 }">link 2</a>

Is it possible to produce the route:

http://localhost/app?foo=1&bar=1

rather than overwriting the current query string? I suspect it's possible by listening to the router events and working it out manually but I wonder if it isn't possible through some configuration?

2 Answers2

0

There is preserveQueryParams that might keep the foo=1 while you navigate to bar=1 i haven't tried it but the docs say it can be used like this

<a [routerLink]="['.']" [queryParams]="{ bar: 1 }" preserveQueryParams>link 2</a>
davidejones
  • 1,869
  • 1
  • 16
  • 18
  • Yeah that doesn't appear to work in conjunction with supplying any query params. –  Feb 24 '17 at 06:52
  • 1
    hmm yea it looks like it gets overridden still. There looks like a good answer here that might help http://stackoverflow.com/questions/41726938/in-angular-2-how-to-preserve-query-params-and-add-additional-query-params-to-rou/41779740 – davidejones Feb 24 '17 at 07:02
  • Cheers for that. That's essentially the same question and has answered mine conclusively (there is no native config solution). If I come up with a simple solution I may post it otherwise this question is redundant. –  Feb 24 '17 at 07:27
0

It's simple enough to get the current query params from the activated route and shallow copying them with modifications as necessary for returning to the router.

In the html:

<a [routerLink]="['.']" [queryParams]="getQueryParams(1)">link 1</a>

in the component:

getQueryParams(id: number) {
  //this.queryParams retrieved by subscribing to the activated route on init
  let queryParams = Object.assign({}, this.queryParams);
  queryParams['foo'] = id;
  return queryParams;
}

Which will return the key value pair object that the router expects for the query params with the parameter in question either added or overridden with any existing ones intact.