Angular Reactive Forms: How to Use FormArray

Tram Ho

In this article we will learn when and how to use FormArray , both in the Component and in the Template, in addition we will see how to customize the validation for it.

Note: To make the article the most effective, please equip yourself with a little more basic knowledge about FormGroup and FormControl .

Why do we need to use FormArray

As you probably already know, when we create an AbstractControl like FormGroup or FormControl , we can use the array as a value. For example

However, this declaration will make it difficult to use the Angular API for each element in the array, as well as synchronize values ​​or use API validate. That’s when we need to use FormArray

What is FormArray

FormArray is responsible for managing a set of AbstractControl , be it FormGroup , FormControl or another FormArray .

Like FormGroup , which groups AbstractControl objects in an object, FormArray does the same thing in an array. Angular has specific APIs to help you manage this collection, which we will talk more about later. Now let’s see how to use it.

Works with FormArray

Let’s say we want to display a form that a user can add, edit, or delete from a skill list

We create a FormArray with the initial value of an empty array. Now see the skills properties:

Like FormControl or FormGroup , FormArray also inherited from the AbstractControl class, so it has many of the same properties, such as valid , dirty , disabled , … In addition, it has an extra controls property to contain an array of elements. by AbstractControl .

Now let’s add a skill:

Each time we call the addSkill method, we add a new FormControl to the controls array. Now use it in the template. First, we need a loop for the controls property of FormArray :

Now, we add each formControl directive control to synchronize each control with its respective element.

It’s simple right. Now let’s try some other methods we can use too:

  • removeAt(index) : This method accepts the index and removes the corresponding AbstractControl .

  • insert(index, AbstracControl) : as opposed to removeAt() , it adds a new AbstractControl to the index position in the controls array.

  • clear() : removes all elements in the array

  • setControl(index, AbstractControl) : unlike the insert method, it replaces the existing control with the passed AbstractControl . In the example below, it’s used in the replace() , to replace the first control with the newly created one.

  • at(index) : AbstracControl the AbstracControl in the array’s index position. In the example below the first control will be returned

Add FormGroup

In the previous section, we learned how to manage a FormControls collection, now let’s see how to manage a FormGroup object in FormArray :

Instead of passing FormControl , we pass FormGroup . Also in the template:

We loop each control, as in the example FormGroup , and pass it to the formGroup directive. Then it’s just syncing the familiar way – pass the name of the control to the formControlName directive.

Use FormArray in FormGroup

Now that you are familiar with the basics, let’s look at some more practical examples where we often use FormGroup inside FormArray

Nothing special here, just create an ordinary FormGroup . Take a look at the template

We add the formGroup directive to the form, and inside, we bind the control name via the formControlName directive. Similarly, to bind to the FormArray ‘s FormArray , we need to do the following 3 steps:

First, we need to add formArrayName to the parent element, it’s like running user.get(skills) .

Next, like in the previous example, we need to loop the controls in the FormArray :

Before getting to the final step, let’s define the skills attribute in the component. The traditional way is to use the getter function to reference the FormArray control from the FormGroup parent.

Or we can declare it as a variable

Now the final step:

Directive formControlName gets the name of the control that we want to match the form element. When working with FormGroup , we pass the key name of the object, for example:

It will look for type user.get('name') . But in this case it’s FormArray so the name will be index. In JS, arrays are a special object whose key is a number (based on their index), so the code should look like this: user.get('skills')[index] => FormControl .

Now let’s see the same process with FormArray containing a collection of FormGroup :

Since FormArray now contains FormGroup , we need to use the formGroupName : user.get('skills')[index] => FormGroup directive user.get('skills')[index] => FormGroup .

When we use formControlName , it will look for the closest parent ControlContainer , in this case the current parent FormGroup object.

FormArray Validation

As mentioned in the beginning, we can apply validation to each AbstractControl as we usually do:

In this case, the validity of the FormArray based on the validity of the AbstractControl . So, as long as there is an invalid AbstractControl , the FormArray ‘s FormArray will be set to false.

We can also apply validate in FormArray directly, for example, we need to validate the array size:

As with any AbstractControl , we can pass the validate function, in which case it will get FormArray every time it changes, and return null if the array is valid, otherwise it returns an object of the specified specified. error.

FormArray with Server Data

Let’s summarize everything with a fairly common example that we need to create FormArray controls from the server data returns.

In this case we cannot use patchValue() or setValue() , because the methods are used to update the value of the already existing controls, while the controls corresponding to the returned data are not yet available. create. Instead, we need to create FormArray from scratch and set values ​​for each controls

In case we already have the controls in FormArray , we simply need to create the controls we need to add, then add it to the array:

The article is quite simple with basic knowledge, hope it is useful to you, if there is something difficult to understand, please comment for me to help you answer!

Source: https://netbasal.com/angular-reactive-forms-the-ultimate-guide-to-formarray-3adbe6b0b61a

Share the news now

Source : Viblo