Angular FormBuilder Example With Reactive Forms

In this article, we will create a reactive form in Angular with the help of FormBuilder API.

The FormBuilder API lets you easily group the form controls without calling the FormControl constructor individually for each control.

Let’s create a simple form that collects the information of a user such as the first name, last name, email address, etc.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  userForm: FormGroup;
  formData: any;
  isFormSubmitted: boolean = false;;

  constructor(private formBuilder: FormBuilder) {

    // Create the form using FormBuilder
    this.userForm = this.formBuilder.group({
      'firstName': ['', Validators.required],
      'lastName': ['', Validators.required],
      'email': ['', [Validators.required, Validators.email]],
      'mobile': ['', Validators.required]
    });

  }

  ngOnInit(): void {
  }

  submit() {

    // Get the value of the form
    this.formData = this.userForm.value;

    // To show form data in template(just for demo)
    this.isFormSubmitted = true;

    // Add your stuff
  }
}

…And here is the template file:

<div class="container">

  <form [formGroup]="userForm">
    <div>
      <input type="text" formControlName="firstName" placeholder="eg. John">
      <label> First Name</label>
    </div>

    <div>
      <input type="text" formControlName="lastName" placeholder="eg. Doe">
      <label> Last Name</label>
    </div>

    <div>
      <input type="email" formControlName="email" placeholder="eg. sample@gmail.com">
      <label> Email</label>
    </div>

    <div>
      <input type="text" formControlName="mobile" placeholder="eg. 9987152436">
      <label> Mobile</label>
    </div>

    <button type="submit" (click)="submit()" [disabled]="userForm.invalid">Submit</button>

    <!-- Show form data on submission(just for demonstration) -->
    <p *ngIf="isFormSubmitted">Form Data: {{formData | json}}</p>

  </form>

</div>

Output:

Angular FormBuilder Example With Reactive Forms

Create a Nested Form Group using FormBuilder

Just like a plain form group, you can call the group() method on the FormBuilder instance to create nested form groups.

For example, let’s say we also want to collect the address of the user along with his name and email address.

But the address field can also contain the street, city, state, country, etc. fields. Therefore, we will nest them inside the address field of the form group.

See the following example:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  userForm: FormGroup;
  formData: any;
  isFormSubmitted: boolean = false;;

  constructor(private formBuilder: FormBuilder) {

    // Create the form using FormBuilder
    this.userForm = this.formBuilder.group({
      'firstName': ['', Validators.required],
      'lastName': ['', Validators.required],
      'address':this.formBuilder.group({
        'city': ['', Validators.required],
        'state': ['', Validators.required],
        'country':['', Validators.required]
      })
    });

  }

  ngOnInit(): void {
  }

  submit() {

    // Get the value of the form
    this.formData = this.userForm.value;

    // To show form data in template(just for demo)
    this.isFormSubmitted = true;

    // Add your stuff
  }
}

Add the template:

<div class="container">

  <form [formGroup]="userForm">
    <div>
      <input type="text" formControlName="firstName" placeholder="eg. John">
      <label> First Name</label>
    </div>

    <div>
      <input type="text" formControlName="lastName" placeholder="eg. Doe">
      <label> Last Name</label>
    </div>

    <div formGroupName="address">
      <div>
        <input type="text" formControlName="city" placeholder="eg. Noida">
        <label> City</label>
      </div>
      
      <div>
        <input type="text" formControlName="state" placeholder="eg. UP ">
        <label> State</label>
      </div>

      <div>
        <input type="text" formControlName="country" placeholder="eg. India">
        <label> Country</label>
      </div>

    </div>

    <button type="submit" (click)="submit()" [disabled]="userForm.invalid">Submit</button>

    <!-- Show form data on submission(just for demonstration) -->
    <p *ngIf="isFormSubmitted">Form Data: {{formData | json}}</p>

  </form>

</div>

Output:

Angular FormBuilder Example with nested Form Groups

Please note that is it important to specify the parent form group name in the template file as well while creating the nested form group as we did using formGroupName="address".

That’s all for this article. Thanks for reading!

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts