Angular 2 : Apply Validator. 在某些情况下需要验证

标签 angular angular2-forms angular-reactive-forms angular-forms

我有一个 angular 2 形式,其中我必须在某些情况下创建一个字段,例如:

description:  ['', Validators.required]

只有在某些类型的条件下才需要此描述字段,例如:

if(true){descReq = true};

如何实现,请指教。提前致谢!

最佳答案

您可以根据表单上另一个控件的值添加或删除验证器:

    testForm: FormGroup;

    constructor(private formBuilder: FormBuilder) {
      this.testForm = this.formBuilder.group({
        condition: [''],
        description: ['']
      });

      this.testForm.controls['condition'].valueChanges.subscribe(result => {
        if (result) {
          this.testForm.controls['description'].setValidators(Validators.required);
          this.testForm.controls['description'].updateValueAndValidity();
        } else {
          this.testForm.controls['description'].setValidators(null);
          this.testForm.controls['description'].updateValueAndValidity();
        }
      });
    }

关于Angular 2 : Apply Validator. 在某些情况下需要验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42238639/

相关文章:

javascript - 每 x 秒刷新一次数据后无法动态更新图标图像

typescript - 将 FormGroup 映射到界面对象

Angular2 patchValue 将值插入数组

javascript - 将数据从父级传递给子级(嵌套表单)

javascript - 动态创建的元素上的 addEventListener 不起作用

forms - 设置初始值Angular 2 reactive formarray

更改路线后,Angular 4 脚本不起作用

angular - 剑道 : Insert a FormGroup at a top into a FormArray

Angular 自定义验证器错误(预期验证器返回 Promise 或 Observable)

angular - 以 react 形式设置和更新表单数组的验证