首页 > 解决方案 > mat-stepper 组件中的每一步

问题描述

我想实现一个垫子步进器,每一步都在不同的组件中,我的问题是如果步骤未完成,防止单击下一步按钮:

parent.html:
<mat-horizontal-stepper>
  <mat-step [stepControl]="stepOneForm [completed]="stepOneForm?.valid">
    <ng-template matStepLabel>Step1</ng-template>
    <child-step-1 
       [stepOne]="stepOneForm"
       (stepOneEmitter)="updateStepOne($event)">
    </child-step-1 >
  </mat-step>
  <mat-step [stepControl]="stepTwoForm [completed]="stepTwoForm?.valid">
    <ng-template matStepLabel>Step2/ng-template>
    <child-step-2 
       [stepTwo]="stepTwoForm"
       (stepTwoEmitter)="updateStepTwo($event)">
    </child-step-2 >
  </mat-step>
</mat-horizontal-stepper>

parent.ts:
stepOneForm: FormGroup;
stepTwoForm: FormGroup;
 //////////
updateStepOne(step: FormGroup) {
    this.stepOneForm = step;
}

updateStepTwo(step: FormGroup) {
   this.stepTwoForm = step;
}

child-1.html
<form [formGroup]="stepOne" (change)="updateStepOne()">
   <mat-form-field>
    <input matInput required type="text" formControlName="title"/>
   </mat-form-field>
   <button mat-button matStepperNext><mat-icon>arrow_forward</mat-icon></button>
</form>
child-1.ts
this.stepOne = this.fb.group({
  title: ['Default title', [
    Validators.required
  ]]
});

updateStepOne() {
  this.stepOneEmitter.emit(this.stepOne);
}

一切正常,除了 stepControl,即使表单无效,也可以进入下一步。

我的错误在哪里?

标签: angularangular-reactive-forms

解决方案


您正在使用[stepControl][completed]同时。在这种情况下stepControl,将被解释为更重要[completed]。如官方文档中所述:

或者,如果您不想使用 Angular 表单,您可以将完成的属性传递给每个步骤,这将不允许用户继续,直到它变为真。请注意,如果同时设置了 completed 和 stepControl,则 stepControl 将优先。

这是链接> https://material.angular.io/components/stepper/overview


推荐阅读