0
0
AngularHow-ToBeginner · 4 min read

How to Use FormArray in Angular: Syntax and Example

In Angular, FormArray is used to manage an array of form controls dynamically inside a reactive form. You create a FormArray by importing it from @angular/forms and adding it to your form group, then you can add or remove controls as needed.
📐

Syntax

The FormArray is a class that holds an array of FormControl, FormGroup, or other FormArray instances. You create it by passing an array of controls to its constructor. It is usually part of a FormGroup to represent a list of similar form elements.

  • FormArray(controls: AbstractControl[]): Creates a new FormArray with the given controls.
  • controls: An array of form controls or groups.
  • push(control: AbstractControl): Adds a new control to the array.
  • removeAt(index: number): Removes control at the specified index.
typescript
import { FormArray, FormControl, FormGroup } from '@angular/forms';

const form = new FormGroup({
  items: new FormArray([
    new FormControl('Item 1'),
    new FormControl('Item 2')
  ])
});

// Add a new control
(form.get('items') as FormArray).push(new FormControl('Item 3'));

// Remove control at index 1
(form.get('items') as FormArray).removeAt(1);
💻

Example

This example shows a simple Angular component that uses FormArray to manage a dynamic list of input fields. Users can add or remove items, and the form value updates accordingly.

typescript
import { Component } from '@angular/core';
import { FormArray, FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-dynamic-form',
  template: `
    <form [formGroup]="form">
      <div formArrayName="items">
        <div *ngFor="let control of items.controls; let i = index">
          <input [formControlName]="i" placeholder="Item {{i + 1}}" />
          <button type="button" (click)="removeItem(i)">Remove</button>
        </div>
      </div>
      <button type="button" (click)="addItem()">Add Item</button>
      <pre>{{ form.value | json }}</pre>
    </form>
  `
})
export class DynamicFormComponent {
  form = new FormGroup({
    items: new FormArray([
      new FormControl('Item 1'),
      new FormControl('Item 2')
    ])
  });

  get items() {
    return this.form.get('items') as FormArray;
  }

  addItem() {
    this.items.push(new FormControl(''));
  }

  removeItem(index: number) {
    this.items.removeAt(index);
  }
}
Output
<form> with dynamic input fields for items, buttons to add/remove items, and JSON display of form value updating live
⚠️

Common Pitfalls

  • Not casting the FormArray when retrieving it from the form group can cause TypeScript errors.
  • Forgetting to update the UI when adding/removing controls leads to inconsistent form state.
  • Using FormArray with template-driven forms is not supported; it works only with reactive forms.
  • Not initializing the FormArray with controls can cause errors when accessing controls.
typescript
/* Wrong: Not casting FormArray */
const items = this.form.get('items');
items.push(new FormControl('New Item')); // Error: Property 'push' does not exist on type AbstractControl | null

/* Right: Cast to FormArray */
const items = this.form.get('items') as FormArray;
items.push(new FormControl('New Item'));
📊

Quick Reference

  • FormArray: Holds an array of controls.
  • push(control): Add a control.
  • removeAt(index): Remove control at index.
  • controls: Access all controls.
  • value: Get current array values.

Key Takeaways

Use FormArray to manage dynamic lists of form controls in reactive forms.
Always cast the retrieved control to FormArray to access its methods safely.
Use push() and removeAt() to add or remove controls dynamically.
Initialize FormArray with controls to avoid runtime errors.
FormArray works only with reactive forms, not template-driven forms.