MatStepper 如何触发步骤的错误状态?

Iva*_*S95 5 javascript typescript angular-material angular angular-material-stepper

我正在我的mat-horizontal-stepper一个组件中实现 a并且我试图让错误状态显示在一个步骤上,如果我在[completed]属性存在时从它移开,但这并false没有发生。

我不确定使用该completed物业或类似的东西是否有一些限制;这是我到目前为止:

组件的 HTML

<mat-horizontal-stepper linear #auditStepper>
     <mat-step label="Choose a Company" [completed]="selectionClient.selected.length > 0">
     </mat-step>

     <mat-step label="Select a PPC Account" errorMessage="Select an Account" [completed]="selectionPPC.selected.length > 0">
     </mat-step>

     <mat-step label="Set Your Targets">  
     </mat-step>
</mat-horizontal-stepper>
Run Code Online (Sandbox Code Playgroud)

组件的 TS

@Component({
  selector: 'app-new-audit',
  templateUrl: './new-audit.component.html',
  styleUrls: ['./new-audit.component.scss'],
  providers: [
    {
      provide:  STEPPER_GLOBAL_OPTIONS,
      useValue: { showError: true }
    }
  ]
})
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我只提供了重要的东西;但是如果我正确地遵循了 Angular Material 文档,我需要做的是将它添加providers到组件(或我的主应用程序模块)中,仅此而已?

因此,例如,如果我进入第 2 步但保持completed条件为假,然后移至另一个步骤,则应触发错误,因为该步骤不再处于活动状态但也未完成。

我只是想了解一切是如何工作的,因为我没有为这个步进器使用反应形式或任何形式,因为我正在使用 MatTable;我只需要用户从表中选择一行(通过 MatTable 的选择功能),如果选择数组有一个元素,那么我可以将该步骤视为“完成”并允许移动到下一步。

Stackblitz 演示 https://stackblitz.com/edit/angular-khyu8u

编辑:

如果我使用 aFormGroup[stepControl]该步骤的属性,错误状态工作得非常好,但我需要它而不需要表单。

yur*_*zui 8

有一种专用方法描述了显示错误所需的条件:

private _getDefaultIndicatorLogic(step: CdkStep, isCurrentStep: boolean): StepState {
  if (step._showError && step.hasError && !isCurrentStep) {
    return STEP_STATE.ERROR;
  }
Run Code Online (Sandbox Code Playgroud)
  • step._showError来自STEPPER_GLOBAL_OPTIONS您在提供者中定义的
  • step.hasError 包括最有趣的部分

以下是所有定义:

@Input()
get hasError(): boolean {
  return this._customError == null ? this._getDefaultError() : this._customError;
}

set hasError(value: boolean) {
  this._customError = coerceBooleanProperty(value);
}

private _getDefaultError() {
  return this.stepControl && this.stepControl.invalid && this.interacted;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,true如果出现hasError 返回

1)我们有stepControl无效状态和当前步骤交互

2)我们传递hasError返回true的输入道具

  • !isCurrentStep 意味着只有在您执行其他步骤时才会显示错误

因此,您可以hasError使用自定义逻辑将属性传递给步骤,例如:

<mat-step ... #step [hasError]="step.interacted" 
Run Code Online (Sandbox Code Playgroud)

分叉的堆栈闪电战