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.
- Opt 1) When the user clicks the item in the table (child component), I cause table component to emit event that causes parent to navigate to the details page. This works because the parent knows where its route currently is, so I could simply do:
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?)
- Opt 2) I pass the current route from the parent component to the table (child). This would just be an input, and I would use this function in the table component to navigate the user:
goToDetails(row): void {
this.router.navigate([`${currentRouteInput}/details/` + row.id], {
queryParamsHandling: "merge",
state: { data: row }
});
}
- Opt3) I find out the current route in the constructor of the table component (with
this.router.events
), and then set it and use it ingoToDetails()
func used above instead of the input param.
- Opt4) ??? For some reason, I thought that there was a way to simply navigate by adding to the current route. For ex: If you were at route
/lists/parent1
I thought there was a router navigate function likerouter.navigateFromRoute.(['/details/${id}'])
and it would just navigate from current route and add to it, so:/lists/parent1/details/${id}
. But the only router navigate funcs I see isnavigate()
andnavigateByUrl()
. Does this exist? I don't know why I thought it does.
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!