Angular: How to update queryParams without changing route


I am trying to update (add, remove) queryParams from a component. In angularJS, it used to be possible thanks to :

$'f', 'filters[]'); // setter
$['filters[]'];    // getter

I have an app with a list that the user can filter, order, etc and I would like to set in the queryParams of the url all the filters activated so he can copy/paste the url or share it with someone else.

However, I don't want my page to be reloaded each time a filter is selected.

Is this doable with the new router?

This question is tagged with angular query-parameters angular-router

~ Asked on 2017-04-29 16:33:32

The Best Answer is


You can navigate to the current route with new query params, which will not reload your page, but will update query params.

Something like (in the component):

constructor(private router: Router) { }

public myMethodChangingQueryParams() {
  const queryParams: Params = { myParam: 'myNewValue' };

      relativeTo: activatedRoute,
      queryParams: queryParams, 
      queryParamsHandling: 'merge', // remove to replace all query params by provided

Note, that whereas it won't reload the page, it will push a new entry to the browser's history. If you want to replace it in the history instead of adding new value there, you could use { queryParams: queryParams, replaceUrl: true }.

EDIT: As already pointed out in the comments, [] and the relativeTo property was missing in my original example, so it could have changed the route as well, not just query params. The proper this.router.navigate usage will be in this case:

    relativeTo: this.activatedRoute,
    queryParams: { myParam: 'myNewValue' },
    queryParamsHandling: 'merge'

Setting the new parameter value to null will remove the param from the URL.

~ Answered on 2017-04-30 13:35:43


@Radoslaw Roszkowiak's answer is almost right except that relativeTo: this.route is required as below:

  private router: Router,
  private route: ActivatedRoute,
) {}

changeQuery() {
  this.router.navigate(['.'], { relativeTo: this.route, queryParams: { ... }});

~ Answered on 2018-01-19 09:06:46

Most Viewed Questions: