首页 > 解决方案 > 通过 *ngFor 为每个角度材料步进步骤提供不同的组件

问题描述

我不知道如何循环遍历步进器的步骤列表并为每个使用不同的组件使用*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但我不够熟悉,无法让它工作。

标签: angularangular-material

解决方案


您可以使用 和 实现它,*ngFor如下ngSwitch所示:

<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>

有关简化示例,请参阅此 stackblitz


推荐阅读