Codementor Events

Mastering Angular Reactive Forms: Unleashing Form Wizardry with FormBuilder, FormGroup, FormArray, and FormControl

Published Jul 02, 2023

In the realm of Angular development, reactive forms are like the Gandalfs of form handling. They possess immense power, flexibility, and the ability to guide users through complex form journeys like a seasoned wizard. At the core of this form sorcery lie four essential elements: FormBuilder, FormGroup, FormArray, and FormControl. Today, we embark on a whimsical adventure through these enchanting tools, exploring their magic with delightful examples that will leave you spellbound. So fasten your seatbelts and prepare to be captivated by the captivating world of Angular Reactive Forms!

FormBuilder: The Spellcaster Extraordinaire

If reactive forms were a magical forest, the FormBuilder would be the ancient sorcerer dwelling within. This mystical being aids us in constructing form controls and groups effortlessly. Think of the FormBuilder as your trusty sidekick, whispering incantations that conjure up form controls with a flick of its virtual wand.

Imagine you have a form with a 'name' and 'email' field. With the FormBuilder, you can create a FormGroup and its corresponding controls like this:

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

// ...

constructor(private formBuilder: FormBuilder) {
  this.formGroup = this.formBuilder.group({
    name: '',
    email: '',
    addresses: this.formBuilder.array([])
  });
}

FormGroup: The Alliance of Form Elements

A FormGroup is like the Justice League of form controls, uniting them to form a cohesive whole. It brings harmony to the chaotic world of form handling. Just as Batman, Wonder Woman, and Superman work together to save the day, FormGroup allows us to manage multiple controls as a single entity.

Let's say we have a form with 'username' and 'password' fields. By creating a FormGroup, we can bind these controls together:

import { FormGroup, FormControl } from '@angular/forms';

// ...

this.formGroup = new FormGroup({
  username: new FormControl(''),
  password: new FormControl(''),
  addresses: new FormArray([])
});

FormArray: The Ever-Expanding Potion Cabinet

In the mystical land of Angular forms, the FormArray acts as an expanding potion cabinet, allowing us to concoct dynamic arrays of form controls. It's perfect for those situations where we need multiple instances of the same field or when our form needs to adapt and grow dynamically.

Imagine a scenario where we need to collect multiple email addresses. With FormArray, we can easily create a dynamic array of form controls:

import { FormGroup, FormControl, FormArray } from '@angular/forms';

// ...

this.formGroup = new FormGroup({
  name: new FormControl(''),
  email: new FormControl(''),
  addresses: new FormArray([
    new FormGroup({
      street: new FormControl(''),
      city: new FormControl(''),
      country: new FormControl('')
    })
  ])
});

To add a new address FormGroup dynamically, we can use the following code:

// ...

addAddress() {
  const addressFormGroup = new FormGroup({
    street: new FormControl(''),
    city: new FormControl(''),
    country: new FormControl('')
  });

  const addresses = this.formGroup.get('addresses') as FormArray;
  addresses.push(addressFormGroup);
}

To remove an address FormGroup dynamically, we can use the following code:

// ...

removeAddress(index: number) {
  const addresses = this.formGroup.get('addresses') as FormArray;
  addresses.removeAt(index);
}

// ...

HTML Template:

Now let's add the HTML template to display and interact with our form:

<form [formGroup]="formGroup">
  <label>
    Name:
    <input type="text" formControlName="name">
  </label>

  <label>
    Email:
    <input type="email" formControlName="email">
  </label>

  <div formArrayName="addresses">
    <div *ngFor="let address of formGroup.get('addresses').controls; let i = index;">
      <fieldset [formGroup]="address">
        <legend>Address {{ i + 1 }}</legend>
        
        <label>
          Street:
          <input type="text" formControlName="street">
        </label>
  
        <label>
          City:
          <input type="text" formControlName="city">
        </label>
  
        <label>
          Country:
          <input type="text" formControlName="country">
        </label>
        
        <button (click)="removeAddress(i)">Remove Address</button>
      </fieldset>
    </div>
  </div>

  <button (click)="addAddress()">Add Address</button>
</form>

In the mystical realm of Angular Reactive Forms, the FormBuilder, FormGroup, FormArray, and FormControl are the wizards and sorceresses that bring our forms to life. Like a spellbinding symphony, they work in harmony to create delightful user experiences and handle even the most complex form journeys. So, let your creativity soar, and let these enchanting tools guide you through the magical realm of form handling in Angular! Happy form wizardry!

Disclaimer: No mythical creatures were harmed in the making of this article. The use of magical metaphors is purely for the purpose of amusement.

Discover and read more posts from Anwarul Islam
get started