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

Angular2/4 - reactive forms, how to dynamically set and clear required validator

我有一个响应式,有两个 select 下拉菜单。根据第一个 select 的值,可能需要也可能不需要第二个。

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

但是,该字段在 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:

"These statuses are mutually exclusive, so a control cannot be both valid AND invalid or invalid AND disabled."

"Disabled controls are exempt from validation checks and are not included in the aggregate value of their ancestor controls."

所以禁用控件应该会自动删除验证,从而将控件标记为有效。

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

  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();
    };
  }