Er Sushil
Er Sushil

Reputation: 1471

How to set or remove queryParams in current route in angular 2 without reloading page

I have this current route:

http://localhost:96/#/pages/settings/devices

I want to set queryParams={name:realTime} to this current route like:

http://localhost:96/#/pages/settings/devices?name=realTime

Is it possible to add or remove queryParams to the current route without reloading the page?

I got the solution for this.

This will not reload Current page

let navigationExtra: NavigationExtras = {
relativeTo: this.activatedRoute,
skipLocationChange: false,
queryParams: { name: 'realTime' }
}
    this.router.navigate(['./', navigationExtra]);

Upvotes: 0

Views: 1884

Answers (2)

basarat
basarat

Reputation: 276383

add or remove queryParams to current route without realoading the page.

Just change the location hash e.g.

window.location.hash = "/pages/settings/devices?name=realTime"

More

The code I presented will work fine. However if you want it to have an impact in the state of your app, you should really check the docs on your router on how to navigate OR write your effects inline with that hash change.

Upvotes: 2

golfadas
golfadas

Reputation: 5531

In order to update the URL without having the router executing navigation build the URL tree and set it on the current location. Don't build the URL by hand.

 const url = this
        .router
        .createUrlTree([{param1: value1, paramN: valueN}], {relativeTo: this.ar})
        .toString();

 this.location.go(url);

location was injected in the component constructor:

import { DecimalPipe, Location } from '@angular/common';
constructor(private location: Location){}

Upvotes: 1

Related Questions