reactive_forms icon indicating copy to clipboard operation
reactive_forms copied to clipboard

Question about nested form groups

Open vicenterusso opened this issue 1 year ago • 2 comments

I have a multistep form (5+ pages), and one big FormGroup/ReactiveForm wrapping all of it.

In one specific step, I have dynamic repeated fields, like "name" and "phone" and I'm using something like this:

'phones': FormArray([
  FormGroup({
    'name': FormControl<String>(value: ''),
    'phone': FormControl<String>(value: ''),
  }),
]),

I don't know if I'm using reactive_forms the correct way here. I'm creating a second FormGroup with "name", "phone" and validators. If this form is valid, I add it to the main form ("phones array). So I'm using the main phones array just to hold the values.

My question is: Is there any better solution in that case? Can I do several nested forms? Any problem with that approach?

Tks!

vicenterusso avatar Aug 14 '22 23:08 vicenterusso

hI @vicenterusso,

Using nested FormGroup to handle a Wizzard (stepper) is completely fine. I use it in my projects, and that is the main reason I have implemented nested FormGroups.

Adding FormGroups to the FormArray dynamically is also correct. But that depends more on your specific implementation. Maybe you don´t need to create a separate FormGroup and add it to the FormArray, maybe you can just add a new FormGroup directly to the array, and bind it to the UI directly from the FormArray (instead of adding it later if it is valid).

joanpablo avatar Aug 15 '22 22:08 joanpablo

Hi, tks for your answer @joanpablo

Maybe you don´t need to create a separate FormGroup and add it to the FormArray, maybe you can just add a new FormGroup directly to the array, and bind it to the UI directly from the FormArray (instead of adding it later if it is valid).

Yeah I tried that, found few examples on Issues sections... but couldn't make it work. If I have 3 fields I need to validade like a group.

If it's bound to the array, how can I add a new empty group? I don't know if I'm making myself clear 😄

vicenterusso avatar Aug 16 '22 01:08 vicenterusso