Angular 设置了 selectedIndex 的步进器 matStepperNext/matStepperPrevious 不工作

Angular Stepper with selectedIndex set matStepperNext/matStepperPrevious not working

我正在使用 matStepper,当我将 selectedIndex 设置为 3 时,我无法使用 next 和 previous 进行导航。我可以单击水平步进器中的 (1),然后像往常一样使用 next/prev。所有表格均有效,我可以在单击 (1) 后使用 1-7 中的下一步进行导航。

注意我有 this.selectedIndex = 3;硬编码

<mat-horizontal-stepper #stepper
                        [linear]="true"
                        [selectedIndex]="this.selectedIndex"
                        (selectionChange)="selectionChange(stepper)">

  <mat-step [stepControl]="form1">
    <app-observer-information></app-observer-information>
  </mat-step>
...
  <mat-step [stepControl]="form7">
    <app-observer-agreement></app-observer-agreement>
  </mat-step>

</mat-horizontal-stepper>



export class ObservationStatementStepperComponent implements OnInit {

  @ViewChild('ObserverInformationComponent') public component1: ObserverInformationComponent;
  ..
  @ViewChild('ObserverAgreementComponent') public component7: ObserverAgreementComponent;

  public selectedIndex: number;

  constructor(private sorDataService: SorDataService) {

    this.selectedIndex = 3; // Number(sorDataService.selectedIndex);
  }

  public ngOnInit() {
  }

  public selectionChange(stepper) {

    this.sorDataService.synchronizeStepper(stepper.selectedIndex + 1);
  }

  /**
   * @see 
   */
  get form1() {
    return this.component1 ? this.component1.form : null;
  }
  ...
  get form7() {
    return this.component7 ? this.component7.form : null;
  }
}

问题在 stackblitz 中重现

<mat-horizontal-stepper linear #stepper [selectedIndex]="1">

https://stackblitz.com/edit/angular-syml71?file=app/create-profile.component.html

快速破解:

HTML:

<mat-vertical-stepper [linear]="true" #stepper>

TS:

 @ViewChild('stepper')
  stepper: MatStepper;
 
 nextClick(): void {
    this.stepper.linear = false;
    this.stepper.selectedIndex = ...;
    setTimeout(() => {
       this.stepper.linear = true;
    });
}

编辑:必须添加 "setTimeout",因为没有它就无法工作了。看起来像是我讨厌的疯狂黑客,但不幸的是别无选择。

To make this work with [linear]="true", use a setTimeout function with 0 delay:

setTimeout(() => {
  this.stepper.selectedIndex = ...;
});

参考:https://github.com/angular/components/issues/8479#issuecomment-444063732

我知道这似乎是愚蠢的解决方案,但你可以使用 stepper.next()

 @ViewChild('stepper')  stepper: MatStepper;
 selectedStepNumber = 2;
 ....
  ngAfterViewInit() {
      setTimeout(() => {
        for (let i = 0; i < this.selectedStepNumber; i++) {
          this.stepper.next();
        }
      }, 0);
    }