0

I am new to Angular and would like to check how do I go about performing custom field validation for FormArray?

The FormArray is dynamic where you can push or remove FormGroup items. The FormGroup consists of field1, field2, field3. If either one of the field is not null, the other fields should be set with validators.required. The form will be valid if all fields are either null or filled.

Thanks.

Below is the code sample:

formA!: FormGroup;

initializeForm(): void {
    this.formA = this.fb.group({
      item1: this.fb.array([this.createItem1()]),
      item2: this.fb.array([this.createItem2()]),
    });
  }

createItem1(): FormGroup {
   return this.fb.group({
       field1: null,
       field2: null,
       field3: null,
   });
}

1 Answer 1

0

Try this.

createItem1(): FormGroup {
  const fg = this.fb.group({
      field1: null,
      field2: null,
      field3: null,
  });
   
  const validatorFn = (control: AbstractControl): { [key: string]: any } | null => {
    const obj = fg.getRawValue();
     
    if (obj.field1 || obj.field2 || obj.field3) {
      return Validators.required(control);
    }
     
    return null;
  };
   
  for (const control of Object.values(fg.controls)) {
    control.setValidators(validatorFn);
  }

  return fg;
}

Also you will need to execute updateValueAndValidity() for all controls when key pressed.

3
  • Hi, i encountered the below at 'fg.controls' when trying this. possible to advise? Type '{ [key: string]: AbstractControl; }' must have a '[Symbol.iterator]()' method that returns an iterator.ts(2488)
    – braveducky
    Nov 24, 2021 at 10:58
  • Fixed my answer. Please check again.
    – N.F.
    Nov 25, 2021 at 0:56
  • Hi, thanks for the help. I did some changes to fit my use case and added additional condition to clear the validators when not required. Overall, it works out in the end.
    – braveducky
    Nov 26, 2021 at 8:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.