0
0
AngularHow-ToBeginner · 4 min read

How to Create Dynamic Form in Angular: Step-by-Step Guide

To create a dynamic form in Angular, use ReactiveFormsModule with FormBuilder, FormGroup, and FormArray. This lets you add or remove form controls at runtime based on user actions or data.
📐

Syntax

Angular dynamic forms use FormGroup to group controls, FormControl for individual inputs, and FormArray to manage a list of controls dynamically. FormBuilder helps create these objects easily.

  • FormGroup: Container for form controls.
  • FormControl: Represents a single input field.
  • FormArray: Holds an array of controls, useful for dynamic lists.
  • FormBuilder: Service to build form controls with less code.
typescript
this.form = this.fb.group({
  name: [''],
  emails: this.fb.array([])
});

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

addEmail() {
  this.emails.push(this.fb.control(''));
}
💻

Example

This example shows a form where users can add multiple email fields dynamically. Each email input is a form control inside a FormArray. Users click a button to add new email inputs.

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

@Component({
  selector: 'app-dynamic-form',
  template: `
    <form [formGroup]="form" (ngSubmit)="submit()">
      <label>Name:</label>
      <input formControlName="name" placeholder="Enter your name" />

      <div formArrayName="emails">
        <div *ngFor="let email of emails.controls; let i = index; trackBy: trackByIndex">
          <input [formControlName]="i" placeholder="Enter email" />
          <button type="button" (click)="removeEmail(i)">Remove</button>
        </div>
      </div>

      <button type="button" (click)="addEmail()">Add Email</button>
      <button type="submit">Submit</button>
    </form>

    <pre>{{ form.value | json }}</pre>
  `
})
export class DynamicFormComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: [''],
      emails: this.fb.array([])
    });
  }

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

  addEmail() {
    this.emails.push(this.fb.control(''));
  }

  removeEmail(index: number) {
    this.emails.removeAt(index);
  }

  submit() {
    console.log(this.form.value);
  }

  trackByIndex(index: number, item: any): number {
    return index;
  }
}
Output
Rendered form with a name input, dynamic list of email inputs, Add Email and Submit buttons, and JSON preview of form values updating as inputs change.
⚠️

Common Pitfalls

Common mistakes when creating dynamic forms in Angular include:

  • Not casting FormArray properly, causing errors when accessing controls.
  • Forgetting to update the form state after adding/removing controls.
  • Not using trackBy in *ngFor, which can cause performance issues.
  • Binding inputs incorrectly without formControlName inside formArrayName.
typescript
/* Wrong: Accessing FormArray without casting */
const emails = this.form.get('emails');
emails.push(this.fb.control('')); // Error: push not a function

/* Right: Cast to FormArray first */
const emails = this.form.get('emails') as FormArray;
emails.push(this.fb.control(''));
📊

Quick Reference

Tips for dynamic forms in Angular:

  • Use FormBuilder to simplify form creation.
  • Use FormArray for lists of controls that change at runtime.
  • Always cast get() results to the correct type (FormGroup, FormArray).
  • Use formArrayName and formControlName directives correctly in templates.
  • Use trackBy in *ngFor for better performance.

Key Takeaways

Use Angular Reactive Forms with FormBuilder, FormGroup, and FormArray to create dynamic forms.
Cast form controls properly to avoid runtime errors when manipulating FormArray.
Add and remove controls dynamically by pushing or removing from FormArray.
Bind form controls correctly in the template using formArrayName and formControlName.
Use trackBy in ngFor loops to optimize rendering of dynamic form controls.