【问题标题】:Angular 5 validation error not shown on input change输入更改时未显示 Angular 5 验证错误
【发布时间】:2023-03-27 15:01:01
【问题描述】:

我的输入控件有问题,如果我输入 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;
            }
        });
    }

【问题讨论】:

    标签: angular angular-forms


    【解决方案1】:

    为此,您需要一个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

    【讨论】:

    • 谢谢。像魅力一样工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    相关资源
    最近更新 更多