Search code examples
angularangular-routingangular5angular-router

How to match an arbitrarily deep path with Angular 5 router?


In my app, every user has access to a bunch of 'items' in a tree of categories and sub-categories. This tree can be of any depth and is dynamically generated. I could query for it, but I would like to prevent having to do that, because all I want is to show 'ItemComponent' in the router-outlet based on urls like this:

localhost:4200/items/cat_a/sub_a/item_x
localhost:4200/items/cat_a/sub_a/sub_sub_a/item_y
localhost:4200/items/cat_b/item_z

Preferably I would like to do this by matching any path that starts with "items/" and parse the rest myself inside 'ItemComponent', but the only way I've been able to get that to work is like this:

{ path: 'items/:a', component: ItemComponent }
{ path: 'items/:a/:b', component: ItemComponent }
{ path: 'items/:a/:b/:c', component: ItemComponent }
{ path: 'items/:a/:b/:c/:d', component: ItemComponent }
{ path: 'items/:a/:b/:c/:d/:e', component: ItemComponent }
...
...

This however seems a bit silly and obviously I'm in trouble if there's ever a path that is just one level deeper than where I chose to stop here. How might I improve this?


Solution

  • Use a matcher in your route definition (instead of a path), and decide which URLs this route should match. In your case, it would match any URL starting with 'items'.