首页 > 解决方案 > Angular - 将分组表单作为没有组的单一表单提交

问题描述

我正在 Angular 中构建一个反应式表单,我想将我的表单拆分为多个组件。

我有一个用于ItineraryCustomer InformationCheckout Information和的组件Additional Information。所有这些组件都具有相同的完整表单,一旦所有组件屏幕完成后将提交,但在移动到下一个屏幕之前,需要检查每个组件的有效性。

例如,假设我的整个表单是使用 FormBuilder 创建的:

// Itinerary
arrivalDate: [new Date()],
arrivalTime: ['12:00'],
arrivalLocation: [''],
returnDate: [new Date()],
returnTime: ['12:00'],
  
// Customer Information
customerName: [null],
customerAddress: [null],
customerCity: [null],
customerState: [null],
customerZip: [null],

// Checkout information
billingCity: [null],
billingAddress1: [null],
billingState: [null],
billingZip: [null],

// Additional Info

notes: [''],
emailAddress: [null],
promoDescription: [null],
referralSource: [null],

所有这些字段都是必需的。

一种想法是将表单分成多个组,如下所示:

this.fb.group({
  itinerary: this.fb.group({ ... })
  customerInfo: this.fb.group({...}_
  ...
})

这样,我可以检查每个“组”作为单个组件内的 [FormGroup] 的有效性。如果我在itinerary组件中,一旦表单组有效,我就可以转到下一页。

问题是现在我的表单值是作为带有嵌套组的大表单提交的,而不是像这样的一个大表单:

myForm.value :
{
  itinerary: { 
    // itinerary form controls here
  },
  customerInfo: { 
    // customerInfo form controls here
  },
  checkoutInfo: { 
    // checkoutInfo form controls here
  },
  additionalInfo: { 
    // additionalInfo form controls here
  }
}

当用户浏览完所有页面后,我需要将所有内容作为一个完整的表单提交,并且不能作为具有嵌套组的表单提交。

Angular 中有没有办法将表单分成不同的组,同时保持表单的原始“完整”值?

标签: angularangular-reactive-forms

解决方案


推荐阅读