Issue
How would I remove a query parameter from the URL? For example from www.expample.com/home?id=123&pos=sd&sd=iii
to www.expample.com/home?id=123&sd=iii
EDIT:
This is my version:
this.activatedRoute.queryParams.subscribe(c => {
const params = Object.assign({}, c);
delete params.dapp;
this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: params });
}).unsubscribe();
Solution
UPDATE: @epelc’s answer below is the up-to-date and correct way to do this: https://stackoverflow.com/a/52193044/5932590.
Unfortunately, there is no clear-cut way to do this currently: https://github.com/angular/angular/issues/18011. However, as jasonaden commented on the linked thread,
This could be done manually by merging the old and new query params, removing the key you don’t want.
Here is one way to do that:
Let’s say you have your queryParams stored in some properties.
class MyComponent() {
id: string;
pos: string;
sd: string;
constructor(private route: ActivatedRoute, private router: Router) {}
ngOnInit() {
this.route.url.subscribe(next => {
const paramMap = next.queryParamMap;
this.id = paramMap.get('id');
this.pos = paramMap.get('pos');
this.sd = paramMap.get('sd');
});
}
}
A method to clear the pos
parameter would look like this:
clearPosParam() {
this.router.navigate(
['.'],
{ relativeTo: this.route, queryParams: { id: this.id, sd: this.sd } }
);
}
This will effectively navigate to the current route and clear your pos
query parameter, keeping your other query parameters the same.