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.

Sign up to request clarification or add additional context in comments.

3 Comments

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)
Fixed my answer. Please check again.
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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.