Search code examples
angularangular5routeparamsangular-router-params

Update routeparams in angular 5


i have a route like this dashboard/tour/2/269, this component represents tour details, and inside that component there are some links which refer to similar tours, so when a user click one of those links i want to reload the component based on the new params like let's say this dashboard/tour/5/150, i tried to use a direct [routerLink] but it attach the new params to the old one to become like this dashboard/tour/2/269/tour/5/150 the route become invalid.

any suggestions please.


Solution

  • You're going to have to inject ActivatedRoute into your component. Your routes would have to be set like this:

    { path: 'person/:id/:office_id', component: PersonComponent },
    

    Then subscribe to the params:

    constructor(private route: ActivatedRoute) {}
    
    ngOnInit() {
      this.route.params
        .subscribe(params => {
          const id = +params['id'];
          const office = +params['office_id'];
          console.log(`Current params are person ID ${id} and office ID ${office}`);
        });
    }
    

    Your routerLink would be:

    [routerLink]="['/persons', 2, 5]"
    

    Here, I have injected an instance of ActivatedRoute as route in my constructor.

    You would need to obtain each of you params that you have listed on your routing for your Dashboard component. In this example, my routing is simple persons/:id where I would get the id from http://localhost:3000/persons/1. So if I had a router link to next person say [routerLink]="['/persons', 2]", this snippet of code would update and provide me an id of 2.

    Based on your current illustration and question, this sounds like the solution your looking for.

    StackBlitz Solution

    https://stackblitz.com/edit/routing-params