如何在提交时验证 Reactive formControl/formArray

How to validate the Reactive formControl/formArray on submit

我有一个 Parent formGroup,其中有一个 formArray 作为控件。这个 formArray 包含一个 Child formGroup.

目的

目的是验证 formArray onSubmit.

中 formGroup 中 specific 字段的所有控件

表单是反应式表单


例如父窗体组

 parentForm = this.fb.group({
    formArray: this.fb.array([]),
  });
 

子窗体组

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

首先我们需要获取childformGroup中特定字段的控件。 我们迭代formArray,得到formGroup的单独控件

对于手动验证和更新改变的值,我们可以使用updateValueAndValidity

submitForm() :void
{
 for(const childGroup of this.formArray().controls)
{
childGroup.get('field1')?.updateValueAndValidity(); //Validate and Update the control manually
}
}

或者您可以使用 updateOn 属性 并将其设置为提交,但有时可能无法正常工作

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