2
votes

I have the below routes, with id being an optional parameter, so the user could load info, or if no id is supplied they could add info. I would like to be able to reuse the component so that the page does not have to reload (api calls in ngOnInit) however because they are two seperate routes angular always creates a whole new component and ngOnInit is called.

I have tried using children but still get the same problem

(this is with the angular 4 router)

const routes: Routes = [
  {
    path: 'stuff/info',
    component: InfoComponent,
  },
  {
    path: 'stuff/info/:id',
    component: InfoComponent,
  },
]
1
are you getting any error doing this way ? - Vamshi
@allanjwalter Please Edit your question with the error you are getting with this code. - Parth Mahida
There is no error, I described the problem in the question clearly, being that angular does not reuse the component - allanjwalter

1 Answers

2
votes

Angular has required, optional, and query parameters. The "optional" parameter you have defined is not "optional" as Angular has defined optional parameters. For "true" optional parameters, you don't need to define them as part of the route configuration. So you can define one route with just stuff/info like this:

const routes: Routes = [
  {
    path: 'stuff/info',
    component: InfoComponent,
  }
]

Then you can add the optional parameter using .navigate or routerLink as shown in the diagram below.

enter image description here

NOTE: As of Angular 4 this should be

this.route.snapshot.paramMap.get('start')

Alternatively, you can always pass the id and pass a 0 or some other known value on a create. I have a complete example of that here: https://github.com/DeborahK/Angular-Routing