Basics of Reactive Forms in Angular

Basics of Reactive Forms in Angular

After a long time, I am writing a technology related blog and actually first blog with actual code example. This blog is about how to use reactive forms in Angular with a real life example. Here, I'll be covering the basics of reactive forms. But, if you are looking for an advanced or a more complex scenario with an example, do check out these blogs:

Let's start with the basics of Angular Reactive Form Libraries. These include:

  • FormBuilder
  • FormControl
  • FormGroup
  • FormArray

Before you start with reactive forms, you need to first import reactive forms module in your module.ts file. Copy & Paste the below line in your app.module.ts or the module file of the component where you want to use it.

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

@NgModule({
  imports: [
    ReactiveFormsModule
  ]
})

FormBuilder in Reactive Forms:

FormBuilder is a very basic element and it's main role is to initialize a reactive form with different types of form elements like FormControl, FormGroup or FormArray.

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

FormControl in Reactive Forms:

FormControl is a simple & straightforward form field. It can be used to bind a normal text field, email field, password field, datepicker, textarea, checkbox, radio or any select dropdown field.

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

FormGroup in Reactive Forms:

FormGroup is used to group the similar kind of controls / form fields e.g. address. An address can comprise multiple fields like city, country, zip code/pin code, landmark, etc. In such scenarios, it is better to create a new FormGroup control and under this, create & bind all these FormControls of city, country, landmark & others.

This helps in handling of validations and grouping form fields make it easy & more convenient when it comes to saving multiple values for same field. For example adding multiple addresses where each address will have its own street number, city, country, etc.

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

FormArray in Reactive Forms:

When there is a need to save multiple records of same type of form fields like multiple addresses or multiple products in a cart. For such scenarios, FormArray is a savior. We may either create an array of FormControl or a FormGroup where this FormGroup will comprise of some FormControls.

For example, to save multiple phone numbers you may create a FormArray of phoneNumber FormControl. While to save an array of addresses, you may create a FormArray of FormGroup where this FormGroup can have some FormControls like streetNumber, city, country, zip/pin code, landmark, etc.

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

This was the basic overview of Reactive Forms. Now, we'll dive into actual programming with a real life example to see how reactive forms work and how to initialize the form values with a default value. In addition to that, we'll also see how to access the form values to display on UI and how to send this form data to web services as payload.

How to create a reactive form?

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

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

    form: FormGroup;

    constructor(private fb: FormBuilder) {}
    
    ngOnInit() {
        this.form.addControl('name', this.fb.control(''));
        this.form.addControl('education', this.fb.array([
            this.fb.group({
                this.fb.control('courseName'),
                this.fb.control('universityName')
            })
        ]));
    }

}

This is your component.ts file code.

Another approach to setting up a basic reactive forms just like above is:

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

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

    form: FormGroup;

    constructor(private fb: FormBuilder) {}
    
    ngOnInit() {
        this.form = new FormGroup({
            name : new FormControl(''),
            education : new FormAarray([
                new FormGroup({
                    courseName: new FormControl(''),
                    universityName: new FormControl('')
                })
            ])
        })
    }

}

This is how you can setup your basic reactive forms in component.ts file with the controls you need. Now, to bind this form on UI, in your template (HTML) file, you need to create a form tag with below code:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <div>
        <input type="text" formControlName="name" placeholder="Enter your Name" />
    </div>
    <div formArrayName="education">
        <ng-container *ngFor="let singleEducation of educationList; let i = index;">
            <div formGroupName="i">
                <input type="text" formControlName="courseName" placeholder="Enter your Course Name" />
                <input type="text" formControlName="universityName" placeholder="Enter your University Name" />
            </div>
        </ng-container>
    </div>
</form>

Here, educationList is the get method to fetch the list of all records from education FormArray field. While i is the index of that record which will uniquely identify the form fields for that record.

So, your final version in your component.ts file should look like:

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

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

    form: FormGroup;

    constructor(private fb: FormBuilder) {}
    
    ngOnInit() {
        this.form.addControl('name', this.fb.control(''));
        this.form.addControl('education', this.fb.array([
            this.fb.group({
                this.fb.control('courseName'),
                this.fb.control('universityName')
            })
        ]));
    }

    get educationList() {
        return this.form.controls["education"] as FormArray;
    }

    onSubmit() {
        // TO DO
        // Add your API integration here..
    }

}

In onSubmit() method, you may add your business logic, web service calls and other URL redirection or displaying of toast / success messages or email notification, depending on your business need.

Summary

What we learnt so far?

In this free tutorial on how to use reactive forms in Angular, we have covered how to import ReactiveFormsModule in our module file and how to use the different form directives in our Angular application.

This is the basic example of Reactive Forms in Angular that includes how to use FormBuilder, FormGroup, FormArray and FormControl with the changes you need to do in your component.ts & HTML template files.

If you are looking for an advanced tutorial on Reactive Forms or a more complex scenario where a reactive form consists of multiple FormArray & FormGroup controls with Child Components & Validations, do check out the following blogs.

Or, if you are just starting out with Angular and not aware about directives, components, modules, and other terms used here, then starting out with the basics of Angular would be good start.

Share this blog on:

Deepak Jain, Full-stack Developer, Blogger and Tech Consultant

About Author

Deepak Jain is an experienced professional full-stack developer, UI/UX designer, ex-startup entrepreneur, passionately writes blog on technology, startups, business ideas. He also shares his own life experiences and creates awesome inspiring stories from the lives of people. Check out full profile