0
<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 部分仅在离开输入字段的焦点后显示。接受按钮被禁用。任何信息如何解决此行为以在用户键入时获取错误消息?

我也试过删除(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};
    };
  }
}
4

4 回答 4

2

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

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

this.control.markAsTouched();
于 2020-11-04T10:35:39.070 回答
0

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

于 2019-04-10T12:29:40.140 回答
0

您可以尝试删除您的第二个条件*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 指令被呈现。

于 2019-04-10T12:29:54.297 回答
-1

解决方案是 ErrorStateMatcher。

于 2019-04-10T16:17:42.377 回答