Blog>
Snippets

Dynamic Form Creation with FormBuilder

Demonstrate the use of Angular's FormBuilder to dynamically add or remove form fields based on user interaction.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
    <form [formGroup]="myForm">
      <div formArrayName="items">
        <div *ngFor="let item of items.controls; let i=index" [formGroupName]="i">
          <input formControlName="name">
          <button (click)="removeItem(i)">Remove</button>
        </div>
      </div>
      <button (click)="addItem()">Add Item</button>
    </form>
  `
})
export class AppComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      items: this.fb.array([])
    });
  }

  get items() {
    return this.myForm.get('items');
  }

  addItem() {
    const itemControl = this.fb.group({
      name: ['', Validators.required]
    });
    this.items.push(itemControl);
  }

  removeItem(index: number) {
    this.items.removeAt(index);
  }
}
This Angular component uses FormBuilder to create a form with an array of dynamically generated items. Each item has an input field for 'name' and a 'Remove' button to remove the item. There is also an 'Add Item' button to add new form groups to the form array. The addItem() and removeItem() methods respectively add and remove FormGroup instances from the form array.