Angular: How to update queryParams without changing route

angular, angular-router, query-string

Solution

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):

import { ActivatedRoute, Router } from '@angular/router';
constructor(
  private router: Router,
  private activatedRoute: ActivatedRoute,
) { }

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

  this.router.navigate(
    [], 
    {
      relativeTo: this.activatedRoute,
      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:

this.router.navigate(
  [], 
  {
    relativeTo: this.activatedRoute,
    queryParams: { myParam: 'myNewValue' },
    queryParamsHandling: 'merge'
  }
);

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

Problem

I am trying to update (add, remove) queryParams from a component. In angularJS, it used to be possible thanks to : ``` $location.search('f', 'filters[]'); // setter $location.search()['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?

Original source

Related problems