Reputation: 29109
I have this situation in which I have an url like
https://example.com?a=1&b=2&c=3
Now I would like to change it to
https://example.com?a=1&b=2&c=4
I tried it with
const navigationExtras: NavigationExtras = {
queryParams: { c: 4}
};
this.router.navigate([], navigationExtras);
But if I do that, c
is indeed updated, but the query params a
and b
are removed. So I tried to add preserveQueryParams: true
but then it seems that you cannot change anything. Any suggestions how to just update one query param?
Upvotes: 1
Views: 1053
Reputation: 3334
Just add one more property queryParamsHandling: 'merge'
in navigationExtras to keep the unchanged queryParams:-
const navigationExtras: NavigationExtras = {
queryParams: { c: 4},
queryParamsHandling: 'merge' // keep the old queryParams if they are not updated
};
this.router.navigate([], navigationExtras);
Another way:-
Or you will need to keep the old values for the unchanged queryParams. So you can keep like:-
const navigationExtras: NavigationExtras = {
queryParams: {
...this._ActivatedRoute.snapshot.queryParams, // get the queryParams from the ActivatedRoute
...{c: 4} // and then update what you want
}
};
And then do the same process as you are doing.
To get the queryParams
from the ActivatedRoute
you need to inject it first:-
constructor(
private _ActivatedRoute: ActivatedRoute // here
) {}
Upvotes: 2
Reputation: 1939
You could try this
constructor(
private router: Router,
private route: ActivatedRoute,
) {}
changeQuery() {
this.router.navigate(['.'], { relativeTo: this.route, queryParams: { ... }});
}
Upvotes: -1