angular form
Dec 04 2018 05:14pm | | Share

Using Angular FormArray

By Quazi Sharar

Angular’s FormsModule consists of a very rich set of tools. Whether you are looking to build an entire form with a FormBuilder, or just manipulate a specific control with FormControl, then FormsModule has all the solutions. 


A very helpful tool in the FormsModule is FormArray. FormArray is useful when there might be multiple fields that are similar but are repeated depending on the application or the clients’ needs.


Typically, when we think of something that’s duplicated over and over again, we immediately think of throwing it into a component and reusing it. Although that is the correct approach in most cases, sometimes it becomes quite a lot of work where something like Angular FormArray can easily do the trick. 


Let’s look at an example. 


On this page, the user can add a friend and then the friend’s email and then send an invite. The user can have multiple friends and add multiple invites at the same time.




Here we can turn the two input fields into a component and just keep adding the component whenever the user clicks the “Add Another Friend” button. But that is way too much work. 


Hello FormArray! With the use of FormArray, all we have to do is just throw the repeating input fields into a FormGroup and then throw that into a FormArray and declare that as part of our main FormGroup. Sounds complex, but in reality it is very simple. 


This is what the TS file looks like.




Here the addFriendForm is the main form group. Within that, there is a property called friends in which we declare the array of inputs. The two inputs here are friendName and email. We use an ngFor loop in the HTML to iterate over the friends array in the form group whenever new fields are added. 


Here is what the HTML looks like:




Notice how we are iterating over addFriendForm.controls.friends.controls array. This is what makes FormArray so useful. This automatically updates the view whenever there are any modifications in the friends FormArray. 


The user updates the FormArray through the “Add Another Friend” button. Once the user clicks this button, the following function runs in the TS file. 




The addFriend function inserts the input fields in the FormArray, causing a change detection to run and update the view. Below is what it looks like when the user has clicked on the button twice.




As we can see throughout this example, FormArray is simple to use and incredibly efficient. It allows control over every input field the same way any FormControl would and makes coding complicated forms even easier!