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');
}