簡體   English   中英

輸入更改未顯示Angular 5驗證錯誤

[英]Angular 5 validation error not shown on input change

我對輸入控件有問題,如果我輸入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;
            }
        });
    }

為此,您需要一個錯誤狀態匹配器 ,以自定義角度材料的驗證行為,導入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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM