We’ve covered reactive and template-driven forms in the past. One of the nice features of reactive forms is the FormArray
class. You can use FormArray
for a form where the number of inputs is dynamic and can increase or decrease:

To achieve the above, we create a FormArray
in our component and add a method so we can append new FormControls
to that array:

Then, we use a @for
block to display all controls of that array in our template, including a button to add new names to the list. Note that we store the index of each control in a local variable i
:

We can even add support for the removal of form elements using the removeAt
method of FormArray
and the index of the element to remove:

And that’s it! We can check that the FormArray
value is updated correctly with the following expression:

You can see that code in action on Stackblitz here. You can read this excellent guest post from Jennifer Wadella on my blog for more information on dynamic forms.