我有一個以 formArray 作為控制元件的父formGroup。此 formArray 包含一個子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
uj5u.com熱心網友回復:
首先我們需要得到子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('')
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/422556.html
標籤:
