angularparent-childrouterangular9navigateurl

How to add to current route and navigate - Angular


I'm working in an Angular 9 project.

I have a table, that's reusable, for now I have two (Parent) components using the table. I want users to be able to select an item on the table and be routed to that items details page. The issue is that these tables are at two different routes (let's say: /lists/parent1 and lists/parent2) and the details page is an extension of those routes. So, if you were clicking an item for parent1's table you need to go to the route /lists/parent1/details/${id} and if you were using parent2's table you'd go to /lists/parent2/details/${id}. I am also passing state data with the router, and setting the queryParamsHandling.

I think can do this in multiple ways, and I'm trying to figure out which would be best.

this.router.navigate([`lists/parent1/details/` + row.id], {
      queryParamsHandling: "merge",
      state: { data: row }
    });

in parent1 and same way in parent2. Down side is that both parents are using functions that are very similar (duplicate code?)


goToDetails(row): void {
    this.router.navigate([`${currentRouteInput}/details/` + row.id], {
      queryParamsHandling: "merge",
      state: { data: row }
    });
  }



Is one way better than the rest? I want to keep this table component reusable. Is there a standard practice for this type of functionality?

I would appreciate any insight and tips, thank you!


Solution

  • you can pass the activated route to the navigate options You inject the route: AcitvatedRoute in the constructor, and set it when you call navigation. Whit that in your table you can call this.router.navigate(row.id, {relativeTo: this.route}); The guide for this.