Angular 15 FormBuilder & FormGroup By Example

Angular 15 FormBuilder & FormGroup By Example

As part of this tutorial, we'll learn how to utilize Angular forms by building a small example that makes use of the FormBuilder, FormGroup, FormArray and FormControl APIs and the latest Angular 15 version.

We'll see how to use Angular FormBuilder, FormGroup, FormArray and FormControl APIs then we'll build a form.

Working with forms in Angular 15

Forms are utilized in the majority of web-based applications because they enable users to enter information while engaging with the application. They are helpful for a variety of tasks such as logging in, looking for information, and providing feedback, to name just a few.

Angular supports two ways, template-driven forms and model-driven or reactive forms, for working with forms, which are defined as follows:

  • The template driven approach makes use of built-in directives to build forms such as ngModel, ngModelGroup, and ngForm available from the FormsModule module.
  • The model driven approach of creating forms in Angular makes use of FormControl, FormGroup. FormArray and FormBuilder available from the ReactiveFormsModule module.

Working with FormBuilder, FormGroup, FormArray and FormControl

As we progress through this tutorial, we'll learn how to create forms in Angular 15 using the FormBuilder class, which allows us to create form controls and groups using factory methods.

You can use the FormBuilder service, with the following steps:

  • Import the FormBuilder service,
  • Inject the FormBuilder service.
  • Generate the form contents.

FormGroup is used to keep track of the value and validity state of a group of FormControl instances.

FormControl is used to keep track of the value and validation status of an individual form control.

We also have the following directives:

  • FormControlName is a directive that links a FormControl in a FormGroup to a form control by name.
  • FormGroupDirective is a directive that binds a FormGroup to a DOM element.
  • FormGroupName is a directive that links a nested FormGroup to a DOM element.
  • FormArrayName is a directive that links a nested FormArray to a DOM element.

Using FormGroup

You can use FormGroup, as follows.

First, you need to import ReactiveFormsModule from the @angular/forms module in your application module and add it to the imports array of @NgModule as following:

import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  imports: [     
        BrowserModule,
        ReactiveFormsModule
  ],
})
export class AppModule { } 

ReactiveFormsModule provides the FormControl, FormGroup and FormArray APIs.

Next, you need to create an instance of FormGroup with the instances of FormControl:

productForm = new FormGroup({
     reference: new FormControl(),
     quantity: new FormControl('11')
}); 

You can provide a default value for the control, by passing it as an argument to the FormControl.

Next, we create a <form> element in our component's template and we use [formGroup]to bind our FormGroup and formControlName directive to bind FormControl elements to HTML form controls:

<form [formGroup]="productForm">
  Reference: <input formControlName="reference"  placeholder="Enter reference">
  Quantity: <input formControlName="quantity"  placeholder="Enter quantity">
  <button type="submit">Submit</button> 
</form> 

These are the steps of this tutorial:

  • Prerequisites
  • Angular Forms, Step 1 — Installing Angular CLI 15
  • Step 2 — Initializing your Angular 15 Project
  • Step 3 — Adding a Reactive Form
  • Step 3.1 — Importing the ReactiveFormsModule
  • Step 3.2 — Importing FormControl and FormGroup
  • Step 3.3 — Creating the FormGroup
  • Step 3.4 — Creating the HTML Form
  • Step 4 — Using the FormBuilder Module
  • Conclusion

Prerequisites

This angular tutorial for beginners is based on the assumption that you already have Node.js and npm installed on your machine.

As well as TypeScript and the fundamentals of Angular. You should be acquainted withcomponents.

Let's see how to install Angular 15 CLI.

Angular 15 Forms, Step 1 — Installing Angular CLI 15

In this step, we'll install and configure Angular CLI 15 on our development machine.

Due to the fact that the Angular CLI is built on top of Node.js, as previously said, make sure you have it installed on your system along with npm.

Angular CLI and forms

Angular CLI is the official tool for initializing and working with Angular projects.

In your command-line interface run the following command:

$ npm install -g @angular/cli

This will install angular/cli v15.0.0 in our system.

That's it, you can now initialize your project using the CLI.

Step 2 — Initializing your Angular 15 Project

Go back to your terminal and run the following commands:

$ cd ~  
$ ng new angular-forms-example

The CLI will prompt you if You would like to add Angular routing. You can type Yes if you need routing in your example and which stylesheet format you would like to use. You can select CSS.

Angular CLI will prepare your project, next you can navigate to your project's folder and serve your app locally using a development server as follows

$ cd angular-forms-example
$ ng serve

Your web application will be available from the http://localhost:4200/ address.

Go to web browser and navigate to the http://localhost:4200/ address:

Step 3 — Adding a Reactive Form

In this step, we'll create an example HTML form. Next, we'll create a form model in the application component using the FormGroup and FormControl APIs. Finally, we'll use the formGroup, formControlName and formGroupName directives to bind our form model to our HTML form.

Step 3.1 — Importing the ReactiveFormsModule

Open the src/app/app.module.ts file and import the ReactiveFormsModule as follows:

import { ReactiveFormsModule } from '@angular/forms';

imports: [
  ...   
  ReactiveFormsModule
],

Step 3.2 — Importing FormControl and FormGroup, FormArray

Next, let's import the FormControl and FormGroup classes in the src/app/app.component.ts file.

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

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

Step 3.3 — Creating the FormGroup

Next, let's create an exampleForm instance of FormGroup with two firstName and lastName form controls as follows:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  exampleForm = new FormGroup ({
    firstName: new FormControl(),
    lastName: new FormControl(),
    alias: new FormArray([ new FormControl("")])
  });

  addNewAlias() {
    this.alias.push(this.fb.control(""));
  }
  get aliases() {
    return this.exampleForm.get("alias") as FormArray;
  }
}

Step 3.4 — Creating the HTML Form

Next, we need to create an HTML form in the src/app/app.component.html file:

<h1>Angular 15 Forms Example</h1>
<form [formGroup]="exampleForm">
  <div class="form-group">
    <label>First Name:</label>
    <input class="form-control" formControlName="firstName">
    <label>Last Name:</label>
    <input class="form-control" formControlName="lastName">
    <div formArrayName="alias">
                    <h3>Add alias</h3>
                    <button (click)="addNewAlias();" >Add another alias </button>
                    <div *ngFor="let  address of aliases.controls;  let i=index">
                        <input type="text" [formControlName] = "i" >
                    </div>
    </div>
  </div>
</form>

We use the formGroup property in the <form> tag to bind the form with our exampleForm form group and we use the formControlName property to bind the <input> tags to individual form controls.

Step 4 — Using the FormBuilder Module

The FormBuilder service provides three factory methods:

  • control(),
  • group(),
  • and array().

The FormBuilder helps you create reactive forms using a simple functional API for creating form controls, form groups, and form arrays.

Inside the src/app/ap.component.ts file import the FormBuilder class from the @angular/forms package as follows:

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

Next, inject FormBuilder in the component constructor as formBuilder


@Component({ selector: 'app-root', 
templateUrl: './app.component.html', 
styleUrls: ['./app.component.css'] }) 
export class AppComponent { 
title = 'app'; 
exampleForm = new FormGroup ({ firstName: new FormControl(), lastName: new FormControl()});

constructor(private formBuilder: FormBuilder) { } 
}

Next add a createForm() method with the following code:

createForm() {
    this.exampleForm = this.formBuilder.group({
      firstName: '',
      lastName: ''
    });
}

Finally call the method from the constructor:

  constructor(private formBuilder: FormBuilder) { 
      this.createForm();
  }

Conclusion

As a recap, forms are used in the vast majority of web-based applications because they allow users to submit information while still interacting with the application, which is advantageous. In addition to logging in, searching for information and offering feedback, they are useful for a range of other activities as well, to mention a few examples.

There are two methods of dealing with forms supported by Angular: template-driven forms and model-driven or reactive forms. In this tutorial, we've seen a simple example of creating a form model and bind it to the HTML <form> element using Angular 15 FormBuilder, FormGroup and FormControl APIs.


  • Date: