使用angular 2+嵌套字段的formGroup条件验证

时间:2020-07-01 11:18:53

标签: angular6 angular5 angular7 angular-reactive-forms

我正在使用反应形式方法。为此,我创建了表单组

this.FormGroup = this.fb.group({
  id: [''],
  name: ['', [Validators.required]],
  type: ['', [Validators.required],
  additionalParams: this.fb.group({
    projectKey: ['']
  })
});

条件

  1. 如果我选择type ='A';那么项目密钥是必填项

  2. 如果我选择type =(A除外),则不是强制性的 为此,我使用了以下条件:

      formControlValueChanged() { 
       const projectKey = this.FormGroup.get('projectKey');
       this.FormGroup .get('type').valueChanges.subscribe(
           (type: string) => {
               console.log(type);
               if (type === 'A') {
                 projectKey.setValidators([Validators.required]);
               }
               else{
                 projectKey.clearValidators();
               }
               projectKey.updateValueAndValidity();
           });
        }
    

但是出现错误。

core.js:1673 ERROR TypeError: Cannot read property 'setValidators' of null

我想给这个条件...有人可以帮助我吗?

0 个答案:

没有答案