Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use FormGroup vs. FormArray?

FormGroup:

A FormGroup aggregates the values of each child FormControl into one object, with each control name as the key.

const form = new FormGroup({   first: new FormControl('Nancy', Validators.minLength(2)),   last: new FormControl('Drew') }); 

FormArray:

A FormArray aggregates the values of each child FormControl into an array.

const arr = new FormArray([   new FormControl('Nancy', Validators.minLength(2)),   new FormControl('Drew') ]); 

When should one be used over the other?

like image 930
jcroll Avatar asked Dec 22 '16 17:12

jcroll


People also ask

Can I use FormArray without FormGroup?

You just need to name the formControls inside your formArray .

Why do we use FormArray in Angular?

The FormArray is a way to manage the collection of Form Controls in Angular. The controls can be a FormGroup , FormControl , or another FormArray . Because it is implemented as an Array, it makes it easier dynamically add controls.

Why do we use FormGroup?

A FormGroup aggregates the values of each child FormControl into one object, with each control name as the key. It calculates its status by reducing the status values of its children. For example, if one of the controls in a group is invalid, the entire group becomes invalid.

Can FormArray contains FormGroup?

The FormArray is a way to Manage collection of Form controls in Angular. The controls can be FormGroup, FormControl, or another FormArray. Because it is implemented as Array, it makes it easier dynamically add controls.


1 Answers

FormArray is a variant of FormGroup. The key difference is that its data gets serialized as an array (as opposed to being serialized as an object in case of FormGroup). This might be especially useful when you don’t know how many controls will be present within the group, like dynamic forms.

Let me try to explain by a quick example. Say, you have a form where you capture a customer's order for Pizza. And you place a button to let them add and remove any special requests. Here is the component's html part:

<section>    <p>Any special requests?</p>    <ul formArrayName="specialRequests">      <li *ngFor="let item of orderForm.controls.specialRequests.controls; let i = index">        <input type="text" formControlName="{{i}}">        <button type="button" title="Remove Request" (click)="onRemoveSpecialRequest(i)">Remove</button>      </li>    </ul>    <button type="button" (click)="onAddSpecialRequest()">      Add a Request    </button>  </section>

and here is the component class defining and handling special requests:

constructor () {    this.orderForm = new FormGroup({      firstName: new FormControl('Nancy', Validators.minLength(2)),      lastName: new FormControl('Drew'),      specialRequests: new FormArray([        new FormControl(null)      ])    });  }    onSubmitForm () {    console.log(this.orderForm.value);  }    onAddSpecialRequest () {    this.orderForm.controls    .specialRequests.push(new FormControl(null));  }    onRemoveSpecialRequest (index) {    this.orderForm.controls['specialRequests'].removeAt(index);  }

FormArray offers more flexibility than FormGroup in the sense that it is easier to manipulate FormControls using "push", "insert" and "removeAt" than using FormGroup's "addControl", "removeControl", "setValue" etc. FormArray methods ensure the controls are properly tracked in the form's hierarchy.

hope this helps.

like image 117
Usman Avatar answered Oct 14 '22 00:10

Usman