0

I have a form like below which contains two formArray,I want to send the request if one of the form arrays has at least value.

  statementForm = this.fb.group({
    favor: this.fb.array([], ),
    against: this.fb.array([],),
  });

This function is used to add the for or against statements :

  createItem(name = '') {
    return this.fb.group({
      statement: name,
    });
  }
2
  • How are values added to the arrays? Commented Mar 2, 2020 at 11:38
  • i have updated the question , hope it clears your doubt. Commented Mar 2, 2020 at 12:03

1 Answer 1

1

You can create your own validator that you can attach to the form group.

The validator can check that values exist in the arrays, and return either an object indicating a validation error or null.

When you submit the form, you can check that the form is valid before submitting.

private getEmptyArrayValidator(...arrayNames: string[]): ValidatorFn {
  return (group: FormGroup): ValidationErrors | null => {      
    const arrays: FormArray[] = arrayNames.map(x => group.get(x) as FormArray);
    // Check that at least one array has at least one item.
    // If you need more complex validation logic, this can be changed easily.
    if (arrays.some(array => array.controls.length > 0)) {
      return null;
    }

    return {
      emptyArrays: 'Lists are empty'
    };
  }
}  

You can attach this to your form group when you create it:

ngOnInit() {
  const validator = this.getEmptyArrayValidator('favor', 'against');
  this.statementForm = this.fb.group({
    favor: this.fb.array([]),
    against: this.fb.array([])
  }, { validators: validator });
}

And then check the form validity when the form is submitted:

onSubmit() {
  if (!this.statementForm.valid) {
    return;
  }

  console.log('submitting');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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