如何清除Angular Material mat-error的验证错误

时间:2017-11-08 14:38:05

标签: angular-material2

我在添加值后尝试重置表单。

表单代码段

<form [formGroup]="addAttributeForm" fxLayout="column">
    <mat-form-field>
      <input matInput formControlName="title" placeholder="Title" required>
      <mat-error>This field is required</mat-error>
    </mat-form-field>
</form>

在组件中

onSubmit(form: FormGroup) {
  // do work
  form.reset();
}

我在观察:

  1. 表单值设置为空。
  2. 但验证消息仍然显示在mat-error。
  3. 我已尝试form.markAsPristine()form.markAsUntouched()并将所有三个结合起来。
  4. 如何重置表单以便不显示mat-error?

3 个答案:

答案 0 :(得分:7)

表单组没有关于是否已提交实际HTML表单的“知识”。它只跟踪表单值/有效性/启用状态。因此,重置表单组会重置值,但不会重置有关表单是否为submitted的任何状态。

要执行此操作,您需要暂停FormGroupDirective并在其上调用resetForm()

表单代码段

<form [formGroup]="addAttributeForm" fxLayout="column">
  <!-- ... -->
</form>

在组件中

@ViewChild(FormGroupDirective) formDirective: FormGroupDirective;

onSubmit(form: FormGroup) {
  // do work
  this.formDirective.resetForm();
}

答案 1 :(得分:4)

此解决方案适用于我。 您需要执行以下操作:

formReset(form: FormGroup) {

    form.reset();

    Object.keys(form.controls).forEach(key => {
      form.get(key).setErrors(null) ;
    });
}

这将重置表单并清除所有错误。

答案 2 :(得分:0)

我能够成功完成此操作的唯一方法是设置一个标志,以便在您想要重置它时隐藏表单,然后使用超时将该标志设置回true。据我所知,目前还没有内置方法可以做到这一点。

showForm = true;

reset(): void {
    this.showForm = false;
    setTimeout(() => this.showForm = true);
}

然后在表单元素的HTML中使用*ngIf="showForm"