Angular 5 输入更改时未显示验证错误

Angular 5 validation error not shown on input change

我的输入控件有问题,如果我键入 501(无效值),除非输入失去焦点,否则不会显示垫错误。当用户输入无效值而不失去焦点时如何显示它? 这是 html

<div class="col-auto form margin-top-17 margin-left-10" [formGroup]="activationPointsFormGroup">
            <mat-form-field style="width:230px!important">
                <input matInput type="number" placeholder="Range" [formControl]="activationPointsFormControl" 
                (keydown.enter)="loadData()">
                <mat-error class="margin-top-1" *ngIf="activationPointsFormControl.errors">
                    Valid values are between -500 and 500 and not 0
                </mat-error>
            </mat-form-field>
 </div>

和打字稿代码

  public activationPointsFormGroup: FormGroup;
  public activationPointsFormControl: FormControl;

  private createForm(): void {
        this.activationPointsFormControl = new FormControl(1, [Validators.required, Validators.min(-500), Validators.max(500)]);
        this.activationPointsFormGroup = new FormGroup({
            timeThresholdFormControl: this.activationPointsFormControl,
        });

        this.activationPointsFormControl.valueChanges.subscribe(value => {

            if (value) {
                this.selectedActivationPoints = value;
            }
        });
    }

为此,您需要 error state matcher,以自定义 angular material 验证行为,导入 ErrorStateMatcher 和...

import {ErrorStateMatcher} from '@angular/material/core';

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.invalid && control.dirty);
  }
}

当控件为 dirty 时,这将显示错误消息。在您的组件中声明一个错误状态匹配器...

matcher = new MyErrorStateMatcher();

然后在您的输入字段中标记它:

<input matInput [errorStateMatcher]="matcher" ...>

这是一个演示,它会在用户输入时显示电子邮件无效...

StackBlitz