Back to course

Dynamic Forms using FormArray

The Complete Angular Developer: From Zero to Hero

50. Dynamic Forms using FormArray

FormArray is the mechanism for handling collections of controls where the number of elements can change at runtime (e.g., adding phone numbers, addresses, or skill tags).

1. Creating the FormArray

We define the FormArray within our FormGroup.

typescript import { FormArray, FormBuilder, Validators } from '@angular/forms';

export class DynamicFormComponent { dynamicForm: FormGroup;

constructor(private fb: FormBuilder) { this.dynamicForm = this.fb.group({ email: ['', Validators.required], phones: this.fb.array([this.createPhoneGroup()]) // Initialize with one item }); }

// Helper function to create a new FormGroup for a phone entry createPhoneGroup(): FormGroup { return this.fb.group({ type: ['home'], number: ['', Validators.required] }); }

// Getter to easily access the 'phones' FormArray in the template get phoneControls() { return this.dynamicForm.get('phones') as FormArray; }

addPhone() { this.phoneControls.push(this.createPhoneGroup()); }

removePhone(index: number) { this.phoneControls.removeAt(index); } }

2. Linking FormArray in the Template

We use formArrayName on the container, and formGroupName on the iterating elements, utilizing *ngFor based on the phoneControls.controls array.

html

  <select formControlName="type">
    <option value="mobile">Mobile</option>
    <option value="home">Home</option>
  </select>
  
  <input type="text" formControlName="number" placeholder="Number">
  
  <button type="button" (click)="removePhone(i)">Remove</button>
</div>

<button type="button" (click)="addPhone()">Add Phone

FormArray is essential for handling repeating data structures efficiently within Reactive Forms.