【问题标题】:reactive form .reset() not clearing the validators反应形式 .reset() 不清除验证器
【发布时间】:2019-06-15 17:29:30
【问题描述】:

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

请帮忙

编辑:我忘记补充说我正在使用角度材料输入。

【问题讨论】:

标签: angular angular-reactive-forms


【解决方案1】:

您需要使用以下内容:

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

来自文档:

clearValidators()

清空同步验证器列表。

updateValueAndValidity()

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

【讨论】:

  • 这个没有任何作用,提交后所有的输入框还是红色的
【解决方案2】:

此问题与: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); 
    });

【讨论】:

  • 这也会删除所有验证器。
  • 感谢 Raju,这对我来说是个新闻。我不知道验证器可以这样被清除。
猜你喜欢
  • 2017-11-22
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 2021-07-06
  • 2021-02-15
  • 2017-11-02
  • 2020-01-27
相关资源
最近更新 更多