Angular 7 + Angular Material => 表单验证错误直到离开焦点才出现

Angular 7 + Angular Material => Form Validation Error not appearing until leaves focus

<form (ngSubmit)="saveChanges()">
    <mat-form-field appearance="outline" >
      <mat-label>New ID</mat-label>
      <input required matInput name="newName" [style]="elemStyles" [formControl]="email">
      <mat-error *ngIf="email.invalid && (email.dirty || email.touched)">
        <p class="error-message" *ngIf="email.errors.duplicateId">ID <strong>already</strong> exists.</p>
        <p class="error-message" *ngIf="email.errors.required">This field is <strong>required.</strong></p>
      </mat-error>
    </mat-form-field>
    <div class="action-buttons">
      <button type="submit" [disabled]="email.invalid" mat-mini-fab class="accept action-button">
        <mat-icon fontSet="fontawesome" fontIcon="fa-check" class="fa-xs action"></mat-icon>
      </button>
      <button type="submit" mat-mini-fab class="cancel action-button">
        <mat-icon fontSet="fontawesome" fontIcon="fa-times" class="fa-xs action"></mat-icon>
      </button>
    </div>
  </form>

mat-error 部分仅显示 AFTER 离开输入字段的焦点。接受按钮被禁用。任何信息如何修复此行为以在用户键入时获取错误消息?

我也尝试删除 (email.dirty || email.touched),但它不起作用:/

我的自定义验证器:

export class DuplicateIDValidator {
  static duplicateIDValidator(pageStructure: PageStructureService) {
    return (control: AbstractControl): {[key: string]: any} | null => {
      return pageStructure.pages.every(page => page.questionId !== control.value.toLowerCase()
        || page.questionId === pageStructure.selectedPages[0].questionId) ? null : {duplicateId: true};
    };
  }
}

如果您希望立即显示错误而不是在触摸控件时(离开焦点时)显示错误,请将 email.invalid && (email.dirty || email.touched) 替换为 email.invalid

您可以尝试删除 *ngIf 上的第二个条件,即删除 (email.dirty || email.touched)

您的代码应如下所示:

<mat-error *ngIf="email.invalid">
  <p class="error-message" *ngIf="email.errors.duplicateId">ID <strong>already</strong> exists.</p>
  <p class="error-message" *ngIf="email.errors.required">This field is <strong>required.</strong></p>
</mat-error>

一旦出现任何错误,这将导致渲染 mat-error 指令。

解决方案是 ErrorStateMatcher。

请注意,在控件的 touched 标志为真之前,<mat-error> 不会显示。这意味着在一个字段的第一个焦点上,然后更改到它,任何 <mat-error> 都不会显示,直到该字段被模糊(并且 touched 标志设置为 true)。

要强制 <mat-error> 在字段首次获得焦点(并且具有无效值)时显示,请将控件标记为已触摸:

this.control.markAsTouched();