I have a routing configuration like so:
[
{
path: 'parent',
component: ParentComponent,
children: [
{
path: 'child-one',
component: ChildOneComponent
},
{
path: 'child-two',
component: ChildTwoComponent
}
]
}
]
Inside the ParentComponent
, I have a button that, when clicked, should add a query parameter to the current route/URL. I've found other answers that suggest this solution:
// inside ParentComponent
constructor(
private router: Router,
private route: ActivatedRoute
) { }
onButtonClick() {
this.router.navigate([], {
relativeTo: this.route,
queryParams: { myparam: true },
queryParamsHandling: 'merge',
})
}
However, using this solution in the ParentComponent
causes the navigation to be relative to the parent route, not the child route. So, for example, if the user is at the URL /parent/child-one
and clicks the button, the browser will navigate to /parent?myparam=true
instead of /parent/child-one?myparam=true
.
Since this code runs in the top component of my application, I'd rather not get into the messy business of traversing the ActivatedRoute
object looking for the appropriate route to pass to the relativeTo
parameter, since there are a lot of edge cases that could pop up.
The Router
object does provide the full, current URL in its url
property, however, using that URL like so won't trigger a navigation event:
onButtonClick() {
this.router.navigate([this.router.url], {
queryParams: { myparam: true },
queryParamsHandling: 'merge',
})
}
Attempting the same thing with this.router.navigateByUrl
also does not trigger a navigation event:
onButtonClick() {
this.router.navigateByUrl(this.router.url, {
queryParams: { myparam: true },
queryParamsHandling: 'merge',
})
}
Adding replaceUrl: true
to the NavigationExtras object (the second parameter to navigateByUrl) also does not cause a navigation event.
this.router.navigateByUrl
instead – Kasabucki Alexandrthis.router.navigateByUrl
with the current URL doesn't trigger a navigation event either. – TrevorreplaceUrl
parameter. – Trevor