【问题标题】:How to validate the Reactive formControl/formArray on submit如何在提交时验证 Reactive formControl/formArray
【发布时间】:2022-01-28 15:43:48
【问题描述】:

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

目的

目的是验证formArray onSubmit内formGroup中特定字段的所有控件。

表单是响应式表单


例如父表单组

 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

【问题讨论】:

    标签: angular validation angular-reactive-forms formarray formgroups


    【解决方案1】:

    首先我们需要获得child formGroup中特定字段的控制权。 我们迭代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('')
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 2019-03-13
      • 2017-05-07
      • 2022-01-25
      • 2018-12-03
      相关资源
      最近更新 更多