[Angular] On the usage of FormArray
FormArray
is a class exported by the FormsModule
, which is quite similar with the FormGroup
.
For reminder, the
FormGroup
gathers and the values of child controls (which can be instances of FormControl, FormGroup or FormArray), and reduces them into a non-iterable object.
As expected, FormArray
outputs values into an object of type array:
FormArray expose a quite useful API:
push
at
- …
** the interesting usecase ** (and the reason why I got recently more interested into): make dynamic fields -> addable -> removable
1. FormsArray in template driven :
There is no current formal implementation of formsArray in template driven
Here is the github issue
The closest hack I could find consists in naming the child controls with increasing numbers (to simulate indexation), and mapping the output to a propper array.
FormArray with simple controls:
FormArray with group controls:
Nb: the hack consists in ‘indexing’ the directive ngModelGroup
.
Main problem: when we do modifications on the formGroup, for example when removing a control. The index of the control will change, but not its name, which will trigger issues.
2. FormsArray in reactive forms :
Nb: to declare a reactive FormArray Group, we need to wrap it first into a formGroup parent: github-issue2
As previously we can declare a ‘simple’ or ‘more complex’ formArray.
FormArray with simple controls:
The main idea consists in:
- using the
formBuilder.array()
method (or instantiating a newFormArray
class) to build our reactive form - using the
formArrayName
directive - attributing an index as the
formControlName
values
FormArray with group controls:
Same procedure, but this time we are using the formGroupName
directive instead of the formControlName
directive.
3. Dynamic fields with FormArrays :
Add fields:
Nb: from now, I will use an ‘alias’ of my FormArray instance, which I set through a getter. This also inforces the typing (otherwise TS would by default infer this is a FormArray)
To add filed, one can simply use the method push
: