通过* ngFor,每个角材料步进器步骤具有不同的组件

时间:2019-12-30 15:03:42

标签: angular angular-material

我不知道如何遍历步进器的步骤列表,并使用*ngFor为每个步进器使用不同的组件。

我目前正在这样做:

<mat-horizontal-stepper
  [linear]="true"
  [labelPosition]="labelPosition"
  (selectionChange)="onSelectionChange($event)"
  [selectedIndex]="currentStep"
  #stepper>

  <mat-step [completed]="steps[0].completed" [label]="steps[0].label">
    <app-my-component-0 [someInput0]="someInput0" (someOutput0)="onSomeOutput0($event)" *ngIf="currentStep === 0"></app-my-component-0>
  </mat-step>
  <mat-step [completed]="steps[1].completed" [label]="steps[1].label">
    <app-my-component-1 [someInput1]="someInput1" (someOutput1)="onSomeOutput1($event)" *ngIf="currentStep === 1"></app-my-component-1>
  </mat-step>
  <mat-step [completed]="steps[2].completed" [label]="steps[2].label">
    <app-my-component-2 [someInput2]="someInput2" (someOutput2)="onSomeOutput2($event)" *ngIf="currentStep === 2"></app-my-component-2>
  </mat-step>

</mat-horizontal-stepper>

有没有更优雅的方式?我认为我需要对ngTemplate做些事情,但是我对它的运作还不够熟悉。

1 个答案:

答案 0 :(得分:1)

您可以使用*ngForngSwitch来实现它,如下所示:

<mat-horizontal-stepper ...>
  <mat-step *ngFor=let step of [0,1,2]" [ngSwitch]="step" [completed]="steps[step].completed" [label]="steps[step].label">
    <app-my-component-0 *ngSwitchCase="0" [someInput0]="someInput0" (someOutput0)="onSomeOutput0($event)"></app-my-component-0>
    <app-my-component-1 *ngSwitchCase="1" [someInput1]="someInput1" (someOutput1)="onSomeOutput1($event)"></app-my-component-1>
    <app-my-component-2 *ngSwitchCase="2" [someInput2]="someInput2" (someOutput2)="onSomeOutput2($event)"></app-my-component-2>
  </mat-step>
</mat-horizontal-stepper>

有关简化示例,请参见this stackblitz