I have a Parent formGroup with a formArray as control. This formArray contains an Child formGroup.
Purpose
The purpose is to validate all controls of a specific field in the formGroup inside the formArray onSubmit.
The form is a reactiveForm
Eg: Parent formGroup
parentForm = this.fb.group({
formArray: this.fb.array([]),
});
Child formGroup
childForm = this.fb.group({
//field which need to be validated onSubmit manually
field1: this.fb.control('',{
validators: myCustomValidator
}),
//this field doesn't need to be validate on submit
field2: this.fb.control('')
}
let formArray = this.parentForm.get('formArray') as formArray //Get it as formArray
formArray.push(this.childForm(data)) //Push the data into the childForm
CodePudding user response:
First we need to get the control of the specific field in the child formGroup. We iterate the formArray and get the individual control of the formGroup's
For manually validate and update the changed value, we can use updateValueAndValidity
submitForm() :void
{
for(const childGroup of this.formArray().controls)
{
childGroup.get('field1')?.updateValueAndValidity(); //Validate and Update the control manually
}
}
Alternatively you can use updateOn property and set it to submit, but it may not work as intended sometimes
childForm = this.fb.group({
//field which need to be validated onSubmit manually
field1: this.fb.control('',{
updateOn: 'submit'
validators: myCustomValidator
}),
//this field doesn't need to be validate on submit
field2: this.fb.control('')
}
