So I have routes like /category/tech
and /category/tech/new
and /category/tech/old
etc
they all use ItemsComponent
So is there any way to define these type routes with optional params like we do in ExpressJS
router.get('/category/tech/:filter?', (req, res) => ...
(here both /category/tech
and /category/tech/xxx
will work)
Or do I have to define them separately like
{path: 'users', component: ItemsComponent},
{path: 'users/:filter', component: ItemsComponent}
So is there any way to define these type routes with optional params like we do in ExpressJS
Simple answer is No, you have to define new route for each separate path.
{path: 'users', component: ItemsComponent},
{path: 'users/:filter', component: ItemsComponent}
Though you can verify the path and determine, if it has optional parameter inside the routed component
using ActivatedRoute
.
As of now, Angular does not let you define optional parameters. So your solution will be to add multiple similar routes - all pointing to the same component. But there is an important thing to note here. If you use the target as component: ItemsComponent
in both routes, since the routes are different, the component will be re-instantiated! - That could be costly depending on your project. If you do not want to re- instantiate the component for every route use redirect
instead. In this case Angular makes sure that the component is instantiated only once.
{path: 'users', redirectTo: 'users/'},
{path: 'users/:filter', component: ItemsComponent}
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With