use same component for different routes with different output

Abel picture Abel · May 14, 2018 · Viewed 11k times · Source

In my application I like to create a master (CRUD) for physician. I have a physician component for creating, editing and listing. A separate component for viewing it. I would like to URL's like

physician/create

physician/list

physician/edit/3

So I created route with children

const routes: Routes = [
{
  path: 'physician',
  children: [
    { path: 'list', component: PhysicianComponent },
    { path: 'create', component: PhysicianComponent },
    { path: 'update/:id', component: PhysicianComponent },
    { path: 'view/:id', component: PhysicianViewComponent }
  ]
}

For create, update and list I want to use the same component, but different output using some conditions inside the component class

Answer

malbarmavi picture malbarmavi · May 14, 2018

Yes, by using the ActivatedRoute service and by that you check route parameters and router url to check which condition to apply but that is hard to maintain. Imagine, you just change the url or change the parameter name so you need to change that at the component. Another way is to add data property to each route something like a flag and based on that flag you apply specific conditions-

const routes: Routes = [
{
  path: 'physician',
  children: [
    { path: 'list', component: PhysicianComponent, data: { kind: 'list' } },
    { path: 'create', component: PhysicianComponent, data: { kind: 'create' } },
    { path: 'update/:id', component: PhysicianComponent, data: { kind: 'update' } },
    { path: 'view/:id', component: PhysicianViewComponent, date: { kind: 'view' } }
  ]
}

component:

ngOnInit() {
  this.activeRoutedService.data.subscribe(data => {
    switch (data.kind) {
      //....
    }
  });
}