对具有不同输出的不同路由使用相同的组件

时间:2018-05-14 07:18:07

标签: angular

在我的应用程序中,我喜欢为医生创建一个主人(CRUD)。我有一个医生组件,用于创建,编辑和列出。用于查看它的单独组件。我想像URL一样

physician/create

physician/list

physician/edit/3

所以我创建了带孩子的路线

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

对于create,update和list我想使用相同的组件,但是使用组件类中的一些条件来输出不同的

4 个答案:

答案 0 :(得分:8)

是的,您可以使用ActivatedRoute服务,并检查路线参数和路由器网址,以检查要应用的条件,但很难确定您只需更改网址或更改参数名称,以便yopu需要更改组件的另一种方式是向每个路由添加数据属性,例如标志,并基于该标志应用特定条件

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

组件:

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

答案 1 :(得分:2)

您只能拥有一个组件并根据URL处理要执行的操作,但我认为它不是最佳解决方案。

如果我是你,我会为每个页面创建不同的组件,使用自己的模板和自己的功能。

如果您不想这样做,则必须在模板和组件的逻辑中使用很多条件。例如:

constructor(private router: Router) {}

get route() { return this.router.url; }

onFormButtonClick() {
  if (this.router.url.endsWith('physician/create')) { ... }
  else if (this.router.url.includes('physician/edit/')) { ... }
}

在你的comoponent中

<ng-container *ngIf="route.endsWith('physician/create')">...</ng-container>
<ng-container *ngIf="route.includes('physician/edit/')">...</ng-container>

答案 2 :(得分:2)

您可以使用ngSwitch

在您的控制器中,确定路线是什么

whichView: string;
constructor(private router: Router) {
  if (this.router.url.endsWith('physician/create')) {
    this.whichView = 'create';
  } else if (this.router.url.endsWith('physician/edit')) {
    this.whichView = 'edit'
  } else {
    this.whichView = 'view'
  }
}

在视图中:

<container-element [ngSwitch]="whichView">
  <some-element *ngSwitchCase="create">...</some-element>
  <some-element *ngSwitchCase="edit">...</some-element>
  <some-other-element *ngSwitchCase="update">...</some-other-element>
  <some-element *ngSwitchDefault>...</some-element>
</container-element>

答案 3 :(得分:1)

您可以设置路径数据并获取组件中的数据以显示不同的输出:

  { path: 'list', component: PhysicianComponent, data: { viewOption: 'list' },
  { path: 'create', component: PhysicianComponent, data: { viewOption: 'create' },
  { path: 'update/:id', component: PhysicianComponent, data: { viewOption: 'update' },

在您的组件中,从ActivatedRoute.snapshot.data

获取数据
constructor(
    private route: ActivatedRoute
) { }

ngOnInit() {
    this.viewOption = this.route.snapshot.data.viewOption;
}
相关问题