【问题标题】:Angular 7 Reactive Forms Conditional "Required" ValidationAngular 7 Reactive Forms 条件“必需”验证
【发布时间】:2019-03-14 20:35:59
【问题描述】:

在开始之前,我不能发布我编写的代码,因为它是包含敏感信息的公司代码,但我会提供虚拟代码..

我正在使用 Angular 7,Reactive Forms,我有一个始终显示在屏幕上的单选按钮。如果您选择“是”选项,则会在其下方显示另一个单选按钮元素。如果您选择“否”,则它不会显示或在当前可见时销毁。 (使用 ngIf*)

我想做的是这样的:

    field: ['', { validators: () => { if (this.isElementShown('blah')) { return Validators.required }}}]

这里是“isElementShown”方法:

  isElementShown(id: string) {
    var element = document.getElementById(id);
       if (document.body.contains(element)) {
          return true;
       }
    return false;
  }

我还通过这样做转储页面提交上的所有“无效”字段:

  const invalid = [];
  const controls = this.form.controls;
  for (const name in controls) {
    if (controls[name].invalid) {
      invalid.push(name);
    }
  }
  console.log(invalid);

该字段最初在页面加载时未显示为无效,当我单击“是”并且第二个单选按钮出现在屏幕上时,它显示为无效。这很好,这就是我期望它做的事情。但是,当我将第一个单选按钮上的选项更改为“否”时,它仍然在控制台中显示为“无效”。即使第二个单选按钮已从 DOM 中销毁。

有人对如何解决这个问题有任何想法吗?我觉得我几乎在那里。我现在只是在放屁!谢谢。

【问题讨论】:

    标签: angular typescript validation conditional reactive-forms


    【解决方案1】:

    Conditional Required你可以通过@rxweb/reactive-form-validator的required验证器来实现。

    您只需在所需的验证器中设置您的条件。

     second:['',RxwebValidators.required({conditionalExpression:(x)=> {
    return x.first == 'yes'
      }})]
    

    TS的完整代码

    this.userFormGroup = this.formBuilder.group({
      first:[''],
      second:['',RxwebValidators.required({conditionalExpression:(x)=> {
    return x.first == 'yes'
      }})]
    })
    

    我已经在根模块中注册了“RxReactiveFormsModule”。

    查看stackblitz example

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 2021-04-13
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 2019-01-04
      • 1970-01-01
      • 2020-02-20
      相关资源
      最近更新 更多