Angular2 / 4 - 反应形式,如何动态设置和清除所需的验证器

时间:2017-08-09 17:15:26

标签: angular angular-reactive-forms

我有一个被动反应,有两个选择下拉列表。根据第一个中选择的值,可能需要或不需要第二个。

这是第一个值更改时触发的代码。它基本上搜索数组以查看它们是否匹配类型,如果有它将它们分配给第二个下拉列表,则添加所需的验证器。如果不是,则禁用该控件并删除验证器。

但是,该字段在else部分仍然是必需的,整个表单被标记为无效。那么缺少什么?

  getCategoryTypes(value: string) {
    let types = this.categories.find(v => v.name === value);
    if (types) {
      this.categoryTypes = types.category_types;
      this.category_type.setValue("");
      this.category_type.setValidators([Validators.required]);
      this.category_type.updateValueAndValidity();
    }
    else {
      this.categoryTypes = [];
      this.category_type.setValidators(null);
      this.category_type.updateValueAndValidity();
    };
  }

供参考:

category_type: FormControl;

更新

在我发现的文档中this

“这些状态是互斥的,因此控件不能同时有效且无效或无效并且已禁用。”

“已禁用的控件不受验证检查,并且不包含在其祖先控件的聚合值中。”

因此,禁用控件应自动删除验证,从而将控件标记为有效。

1 个答案:

答案 0 :(得分:1)

if(类型)检查不起作用,但我也发现没有必要删除并重新添加验证,我只能禁用并重新启用控件。所以解决方案是:

  getCategoryTypes(value: string) {
    let types = this.categories.find(v => v.name === value).category_types;
    if (types.length > 0) {
      this.categoryTypes = types;
      this.category_type.setValue("");
      this.category_type.enable();
      this.category_type.updateValueAndValidity();
    }
    else {
      this.categoryTypes = [];
      this.category_type.disable();
      this.category_type.updateValueAndValidity();
    };
  }