Angular Reactive Form with Dynamic Fields

Angular Reactive Form with Dynamic Fields

Angular Reactive Form with Dynamic Fields

FormArray lets you manage a variable number of controls inside a reactive form.

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

@Component({
  selector: 'app-contact-form',
  standalone: true,
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <input formControlName="name" placeholder="Name" />

      <div formArrayName="phones">
        @for (ctrl of phones.controls; track $index; let i = $index) {
          <div>
            <input [formControlName]="i" placeholder="Phone {{ i + 1 }}" />
            <button type="button" (click)="removePhone(i)">Remove</button>
          </div>
        }
      </div>

      <button type="button" (click)="addPhone()">+ Add Phone</button>
      <button type="submit">Submit</button>
    </form>
  `,
})
export class ContactFormComponent {
  private fb = inject(FormBuilder);

  form = this.fb.group({
    name:   ['', Validators.required],
    phones: this.fb.array([this.fb.control('', Validators.required)]),
  });

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

  addPhone(): void {
    this.phones.push(this.fb.control('', Validators.required));
  }

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

  onSubmit(): void {
    if (this.form.valid) console.log(this.form.value);
  }
}
All Comments