Angular router: how to replace param?

fedor.belov picture fedor.belov · Jun 10, 2018 · Viewed 23.4k times · Source

Let's suppose I've got 3 urls: /:projectId/info, /:projectId/users, /:projectId/users/:userId/profile. All of them have param projectId. UI has a component to switch from one project to another. So I need:

  1. Get current URL
  2. Change param by name (e.g. projectId)
  3. Navigate to new url

So I need something like this.router.replaceParam(currentUrl, {projectId: 'project_id_2'}) which will transform /project_id_1/users/user_id_1/profile into /project_id_2/users/user_id_1/profile (and any other URL with :projectId param)

I thought it's a simple and common problem but didn't find a solution in 1 hour. Suggested here solution doesn't work as noted in the last comment

Answer

khush picture khush · Jun 19, 2018

To navigate to particular link from current url, you can do something like this,

 constructor(private route: ActivatedRoute, private router: Router){}
 ngOnInit() {
     this.route.params.subscribe(params => {
         // PARAMS CHANGED ..    

         let id = params['projectid'];    
     });
 }
 navigate(){
     this.router.navigateByUrl(this.router.url.replace(id, newProjectId));
     // replace parameter of navigateByUrl function to your required url
 }

On ngOnInit function, we have subscribed to params so we can observe and executes our statements on any change in url parameter.