反应形式.reset()不清除验证器

时间:2019-01-22 09:22:45

标签: angular angular-reactive-forms

我正在Angular6中使用一种简单的反应形式。

this.phoneForm = this._formBuilder.group({
  oldMac: new FormControl('', Validators.compose([
    Validators.required,
    Validators.pattern('')
  ])),
  newMac: ['', Validators.required],
  newModel: ['', [Validators.required]],
  targetCluster: ['', [Validators.required]],
  ownerUser: ['', [Validators.required]]
}, { updateOn: 'blur' });

要重置我正在使用this.phoneForm.reset();,它正在清除表单,但没有清除验证器,我的表单显示为无效。

请帮助

编辑:我忘了补充一点,我使用的是角材料输入。

2 个答案:

答案 0 :(得分:1)

您需要使用以下内容:

this.phoneForm.clearValidators();
this.phoneForm.updateValueAndValidity();  
this.phoneForm.reset();

从文档中

  

clearValidators()

     

清空同步验证器列表。

     

updateValueAndValidity()

     

重新计算控件的值和验证状态。

答案 1 :(得分:0)

此问题与:https://github.com/angular/material2/issues/4190有关 重置只是清除表单内容,从而触发验证失败,因为未提供任何值。 为了从本质上重置为基本状态,应将表格标记为原始或未更改。

    Object.keys(this.form.controls).forEach(key => {
      let control = this.form.controls[key];
      control.reset(); // clear control's contents.

      // resets the control the before user interaction state
      control.markAsPristine(); 

      // As raju stated this will not only remove errors but also remove all validators.
      control.setErrors(null); 
    });
相关问题