【问题标题】:Angular2/4 - reactive forms, how to dynamically set and clear required validatorAngular2/4 - 反应形式,如何动态设置和清除所需的验证器
【发布时间】:2018-01-17 17:03:18
【问题描述】:

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

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

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

“这些状态是互斥的,所以一个控件不能同时有效和​​无效或无效和禁用。”

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

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

【问题讨论】:

  • 没有足够的信息来重现该问题。这里的代码对我来说看起来不错。也许创建一个展示问题的 plunker?
  • 它肯定执行了这个逻辑的适当分支吗?
  • 你试过这个吗:this.category_type.clearValidators();
  • 我相信这是因为你先设置了验证器,然后 getCategoryTypes() 可能没有再次运行?没有足够的代码,但我遇到了与复选框类似的问题。本质上,当值更改或无法满足 DeborahK 提到的 this.control.clearValidators(); 的要求时,您必须删除验证器;
  • @DeborahK 是的,它肯定在执行 else 分支,我通过登录控制台对其进行了测试。我也试过 clearValidators()。

标签: angular angular-reactive-forms


【解决方案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();
    };
  }

【讨论】:

    猜你喜欢
    • 2019-06-15
    • 2017-11-22
    • 1970-01-01
    • 2020-09-27
    • 2018-02-03
    • 1970-01-01
    • 2017-11-02
    • 2018-12-20
    • 2017-11-13
    相关资源
    最近更新 更多