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

时间:2018-03-20 18:06:21

标签: angular angular-forms

输入控件存在问题,如果输入501(无效值),除非输入失去焦点,否则不显示mat-error。当用户键入无效值而没有输入失去焦点时,如何显示? 这是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;
            }
        });
    }

1 个答案:

答案 0 :(得分:3)

为此,您需要error state matcher来自定义角度材质验证行为,导入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