首页 > 解决方案 > 角度5,反应形式 - 重置所需的表单控件不会重置输入下所需的错误

问题描述

在模板中,我有一个通过按下按钮打开的表单-

     <form [formGroup]="person"
          (ngSubmit)="onSubmitNewPerson()"
          #formDirective="ngForm">

            <mat-form-field>
                <input matInput formControlName="firstName" required>
            </mat-form-field>

            <mat-form-field>
                <input matInput formControlName="lastName" #last required>
            </mat-form-field>
</form>

在组件中我有这个代码 -

  @ViewChild('formDirective') formDirective: FormGroupDirective;

 this.person = this.formBuilder.group({
            lastName: ['', Validators.required],
            firstName: ['', Validators.required]
        });

关闭按钮后,我运行此功能-

   this.formDirective.resetForm();//hack that I saw in some question
    this.person.reset();

但是再次打开表单后,我立即看到输入下方的红色错误。

我也试过这个-

    this.person.get('firstName').markAsUntouched();
   this.person.get('lastName').markAsUntouched();
     this.person.get('firstName').markAsPristine();
    this.person.get('lastName').markAsPristine();

但这也不起作用。

知道如何解决吗?

标签: javascriptangulartypescriptangular-reactive-forms

解决方案


当我想重置验证器时,我使用了以下内容:

    this.person.get('firstName').clearValidators();
    this.person.get('firstName').updateValueAndValidity();

推荐阅读