我如何强制显示验证错误?

问题描述 投票:0回答:1

我有一个标准的材料表格,一切都很好。

[提交表单时,我有选择地收到验证错误,我将这些匹配键循环到控件,然后设置验证错误。像这样删除循环。

我并不认为这很重要,但这是相关的部分。

 const control = this.form.get(key);
 if (control) {
     control.setErrors({
         server: response.validationErrors[key]
     },{
         emitEvent: true
     });

     // I was trying things like
     // control.markAsTouched() but it did nothing
 }

目前,我的表单显示的是红色字段,很好。

shows red fields

但是在我与该字段进行交互之前,它不会显示错误消息,这很烦人。

shows red fields after interaction displaying the error

但是,可能导致此问题的原因是,我没有使用<form (submit)="onSubmit(model)">语法。因此,在我的按钮上,我没有使用type=submitattr.form="my-form"

因此,传统上不会提交任何表格。我相信这可能是一个问题。

如果我阅读材料Form Field Docs。它告诉我:

错误消息可以通过添加以下形式显示在表单字段下划线下表单字段内的mat-error元素。错误最初被隐藏并在用户具有以下条件后显示在无效的表单字段中与元素交互或已提交父表单。

注意最后一行吗?我发现很难正确理解它。

问题:

是否有一种机制可以让我立即强制显示这些验证错误,而无需进行交互?

angular angular-material2
1个回答
0
投票

签出此StackBlitz link

这是您的html模板文件... [[errorStateMatcher] =“ matcher”很重要。

<form class="example-form">
    <mat-form-field class="example-full-width">
    <input matInput placeholder="Email" [formControl]="emailFormControl"
       [errorStateMatcher]="matcher">
    <mat-hint>Errors appear instantly!</mat-hint>
    <mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
          Please enter a valid email address
    </mat-error>
    <mat-error *ngIf="emailFormControl.hasError('required')">
          Email is <strong>required</strong>
    </mat-error>
   </mat-form-field>
 </form>

以及您的ErroStateMatcher类文件。

export class MyErrorStateMatcher implements ErrorStateMatcher {
      isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
     const isSubmitted = form && form.submitted;
      return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
      } 
}
© www.soinside.com 2019 - 2024. All rights reserved.