5

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}
Shifatul
  • 2,277
  • 4
  • 25
  • 37
  • Possible duplicate of [Angular 2 optional route parameter](https://stackoverflow.com/questions/34208745/angular-2-optional-route-parameter) – Amit Chigadani Jun 25 '18 at 04:31
  • check this https://codecraft.tv/courses/angular/routing/parameterised-routes/#_optional_params – Fartab Jun 25 '18 at 06:24

2 Answers2

9

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.

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
9

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!

James Poulose
  • 3,569
  • 2
  • 34
  • 39