allanjwalter
allanjwalter

Reputation: 175

Angular Reuse Component in different routes

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,
  },
]

Upvotes: 3

Views: 4539

Answers (1)

DeborahK
DeborahK

Reputation: 60518

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

Upvotes: 2

Related Questions