Issue
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,
});
}
Solution
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.
Answered By - N.F.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.