← Back to Angular, page 6

angular-0107 · Easy fresher

How do you add and remove form fields at run time with FormArray in a reactive form?

A FormArray holds an ordered list of controls or groups. Build it with FormBuilder, loop over its controls in the template, add a new group with push, remove with removeAt, and read the whole result from the parent form's value.

Full answer

Use a FormArray when the number of fields is not fixed: phone numbers, subjects with marks, or answers to a quiz.

Set-up:

  1. The parent is a FormGroup that has an array property: subjects: this.fb.array([ this.newSubject() ]).
  2. A small factory returns a group for one row: fb.nonNullable.group({ name: ['', Validators.required], marks: [0, [Validators.min(0), Validators.max(100)]] }).
  3. A getter exposes the array with the right type, for the template and for methods.
  4. The template loops over subjects.controls and uses [formGroupName]="i" for each row, so each row binds to its group.
  5. push adds a row, removeAt(i) removes one, and clear() empties the array.

Reading and validation:

  • form.value.subjects is an array of plain objects. form.getRawValue() also includes disabled controls.
  • The array is invalid when any child is invalid, so form.invalid blocks submit.
  • Add validators on the array itself for rules such as "at least one subject": Validators.minLength(1).

Tips for the template: use track with the control object, not the index. Using the index makes Angular reuse DOM elements wrongly after a removal and can confuse focus. Give remove buttons a label that includes the row number for screen readers.

Typed forms: fb.nonNullable.group and FormArray<FormGroup<...>> give types, so controls[0].controls.marks.value is a number.

typescript
import { Component, inject } from '@angular/core';
import { FormArray, FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';

@Component({
  selector: 'app-marks-form',
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="submit()">
      <div formArrayName="subjects">
        @for (row of subjects.controls; track row; let i = $index) {
          <div [formGroupName]="i">
            <input formControlName="name" [attr.aria-label]="'Subject ' + (i + 1)" />
            <input type="number" formControlName="marks" [attr.aria-label]="'Marks ' + (i + 1)" />
            <button type="button" (click)="remove(i)" [attr.aria-label]="'Remove subject ' + (i + 1)">Remove</button>
          </div>
        }
      </div>
      <button type="button" (click)="add()">Add subject</button>
      <button type="submit" [disabled]="form.invalid">Save</button>
    </form>
  `,
})
export class MarksFormComponent {
  private readonly fb = inject(FormBuilder);

  readonly form = this.fb.nonNullable.group({
    subjects: this.fb.array([this.newSubject()], Validators.minLength(1)),
  });

  get subjects(): FormArray<ReturnType<MarksFormComponent['newSubject']>> {
    return this.form.controls.subjects;
  }

  newSubject() {
    return this.fb.nonNullable.group({
      name: ['', Validators.required],
      marks: [0, [Validators.min(0), Validators.max(100)]],
    });
  }

  add(): void {
    this.subjects.push(this.newSubject());
  }

  remove(index: number): void {
    this.subjects.removeAt(index);
  }

  submit(): void {
    console.log(this.form.getRawValue());
  }
}

Angular 20.3, strict template check passes. A Karma test adds a row, checks that the form is invalid while the new name is empty, then removes the row.

Key points

  • `FormArray` is a dynamic list of controls or groups.
  • Add with `push`, remove with `removeAt`, empty with `clear`.
  • Use `[formGroupName]="i"` per row, and `track` the control object.
  • Validate the array (`minLength`) and each row.

Common mistakes

  • Tracking rows by index, which breaks DOM reuse after removal.
  • Forgetting `formArrayName` or `formGroupName` in the template.
  • Creating one shared group object and pushing it twice.

Follow-ups

  • How would you validate that subject names are unique?
  • What is the difference between `value` and `getRawValue()`?
  • How would you load existing data into the array?

Tips

  • Show the row factory. It is the core of the pattern.
  • Mention `track` by object.
  • Mention typed forms.

Evaluation rubric

  • Builds and renders a FormArray correctly.
  • Adds and removes rows.
  • Handles validation and typing.