gpt4 book ai didi

angular-material2 - 如何清除角 Material 垫错误的验证错误

转载 作者:行者123 更新时间:2023-12-04 23:38:19 26 4
gpt4 key购买 nike

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

表单代码段

<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()并结合了所有这三个。

  • 如何重置表格,以免显示错误垫?

    最佳答案

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

    为此,您需要保留 FormGroupDirective 并在其上调用resetForm()

    表单代码段

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

    在组件
    @ViewChild(FormGroupDirective) formDirective: FormGroupDirective;

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

    关于angular-material2 - 如何清除角 Material 垫错误的验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182445/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com