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

前端之家收集整理的这篇文章主要介绍了angular-material2 – 如何清除Angular Material mat-error的验证错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_502_0@
@H_502_0@
我在添加值后尝试重置表单.

表单代码片段

<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();
}

我在观察的内容

>表单值设置为空.
>但验证消息仍然显示在mat-error中.
>我尝试过form.markAsPristine(),form.markAsUntouched()并将这三者结合起来.

如何重置表单以便不显示mat-error?

解决方法

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

要做到这一点,你需要保持FormGroupDirective并在其上调用resetForm().

表单代码片段

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

在组件中

@ViewChild(FormGroupDirective) formDirective: FormGroupDirective;

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

猜你在找的Angularjs相关文章