How to navigate to the same URL but change (or add if missed) one of the query params

Issue

Is there a simple way to achieve that?

For example I want to set/change query parameter qp to the value 111:

/p1/ ----> /p1/?qp=111
/p2/ ----> /p2/?qp=111
/p1/?ee=22 ----> /p1/?ee=22&qp=111
/p1/?ee=22&qp=222 ----> /p1/?ee=22&qp=111

etc

I tried to do router.navigate([], { queryParams: { qp: '111' } });
but it just replaces all query params with qp=111, if I set queryParamsHandling: 'preserve' URL is not changing at all…

Solution

First, we need to get the existing query params

const queryParams: Params = Object.assign({}, this.activatedRoute.snapshot.queryParams);

// Do something with the params
queryParams['myParam'] = 'myNewValue';

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

Answered By – Suresh Kumar Ariya

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.