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



我在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();,它正在清除表单但不清除验证器,我的表单显示为无效。

请帮忙

编辑:我忘了补充一点,我正在使用角度材料输入。

您需要使用以下方法:

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

从文档中:

clearValidators()

清空同步验证程序列表。

updateValueAndValidity()

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

此问题与以下方面有关: 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); 
    });

最新更新