angularformarrayformgroups

Angular FormArray setValidators does not work when setting dynamically


I have a formGroup which has a formArray, which contains of {key: '', value: ''} formGroups. I want to make the value formControl to be required when the key formControl is not empty. I have implemented the following function inside form.valueChanges. This does not work. What am I doing wrong?

this.form.valueChanges
  .pipe(
    distinctUntilChanged()
  )
  .subscribe({
    next: result => {
      (this.form.get('i18nDescription') as FormArray).controls.forEach((formGroup: FormGroup) => {
        const formGroupValue = formGroup.value;

        if(formGroupValue.key !== '' && formGroupValue.value === '') {
          formGroup.controls['value'].setValidators(Validators.required);
          formGroup.updateValueAndValidity({ emitEvent: false });
        }
      });
    }
  });

Solution

  • You are accessing formGroup value properties to add validation into value formControl that is not going to work any more, You have to directly access formGroup it self to add conditional validation.

    this.form.valueChanges
      .pipe(
        distinctUntilChanged()
      )
      .subscribe({
        next: result => {
          (this.form.get('i18nDescription') as FormArray).controls.forEach((formGroup: FormGroup) => {
            if(formGroup.get('key').value != null) {
              formGroup.get('value').setValidators(Validators.required);
              formGroup.get('value').updateValueAndValidity({ emitEvent: false });
            }
          });
        }
      });
    

    Update your code to above code

    Hope it works for you

    Thanks!