Search code examples
angularangular-router

How to replace route parameters in active route


I have the following route

{
    path: ':teamId/sample',
    component: SampleComponent
}

Let's say I'm currently at the route 10/sample, How can I navigate using the Router to x/sample where the value x is obtained dynamically (observable subscription, etc).

If I have to replace query params for the active URL I would simply do

this.router.navigate([], {
    queryParams: { // updated params },
    queryParamsHandling: 'merge',
});

but how to achieve the same with Route params?

EDIT: I have a bunch of such routes and the route param isn't always the first part of the route, It can be even be like /xyz/abc/:teamId/foo, I am looking for a generic solution which also handles such cases.

Stackblitz


Solution

  • This should do the trick:

    this.randomNumberService.data$.subscribe(random => {
      const snaphsot = this.activatedRoute.snapshot.pathFromRoot;
    
      this.router.navigate(snaphsot.slice(1).map(s => {
        if (s.routeConfig.path === ':teamId') {
          return random;
        }
        return s.url.join('/');
      }), {preserveQueryParams: true})
    });
    

    Important to note:

    For this solution you have to configure the ':teamId' path as it's own segement, like:

    {
        path: ':teamId',
        children: [
          {path: 'after', component: SampleComponent}
        ]
      },
    

    Otherwise the check s.routeConfig.path === ':teamId' will resolve to false.

    Stackblitz