Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2+ routing - optional route params

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}
like image 226
Shifatul Avatar asked Jun 25 '18 04:06

Shifatul


2 Answers

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.

like image 195
Amit Chigadani Avatar answered Oct 13 '22 11:10

Amit Chigadani


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!

like image 34
James Poulose Avatar answered Oct 13 '22 11:10

James Poulose