
Learn Reactive Forms in Angular: A Complete Beginner’s Guide
Learn about reactive forms in Angular, including an overview of forms, their types, and how to build dynamic, scalable form structures efficiently.
What are Forms in Angular?
In Angular, Forms are a key part of creating dynamic and interactive web applications in Angular. They allow users to enter data, submit it, and interact with the application's interface.
Types of Forms in Angular
Angular offers two main methods for working with forms:
- Template-driven forms: Template-driven forms are primarily created and managed in the component's template using directives such as ngModel and ngForm.
- Reactive forms: Reactive forms are created programmatically in the component class using form control objects.
Angular Reactive Form
Reactive forms in Angular provide a more programmatic and flexible approach to constructing forms compared to template-driven forms.
Using the reactive forms, you can define the form model and its behavior directly in the component class using TypeScript language, and it allows for greater control and customization options.
Note: Reactive forms are especially useful for complex forms or forms with dynamic behavior.
Prerequisites
The prerequisites to create reactive forms in Angular are:
- FormGroup: A FormGroup is a collection of form controls that represents the entire form structure and holds the current value and state of each form control.
You create a FormGroup by instantiating the FormGroup class in the component class.
FormControl: A FormControl represents an individual form control, such as an input field or a select dropdown. It holds the current value and validation state of the control.
You create a FormControl by instantiating the FormControl class in the component class.
FormBuilder: The FormBuilder service offers easy-to-use methods for creating instances of FormGroup and FormControl.
It simplifies the process of creating reactive forms by abstracting some of the boilerplate code.
You can inject the FormBuilder service into the component constructor and use it to create form controls and groups.
Except for the important points mentioned above, we also have additional elements of reactive forms, such as validators and formArray, which are not necessary to discuss.
How to add a single FormControl
In this section, we will discuss how to add a single form control to a reactive form. Users will enter their name or any similar value into an input field. The form will capture that input value and display the current value of the form control element.
To add a single FormControl, please follow the following steps:
1. Register the reactive forms module: You need to register or import the “ReactiveFormsModule” into your ‘NgModules’ imports array as follows:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AgePipePipe } from './pipes/age-pipe.pipe';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
AgePipePipe,
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }2. Import the necessary module: Ensure that all necessary modules are imported into your app.component.ts file and injected into the constructor. This typically includes FormBuilder and FormGroup from @angular/forms.
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit{
constructor(private fb: FormBuilder){
}
myForm: FormGroup = new FormGroup({});
ngOnInit(): void {
this.myForm = this.fb.group({
'name': new FormControl(''),
});
}
}3. Attach the form control to the template: Make sure that the formGroup and formControl are attached to your template.
<form [formGroup] = "myForm">
<input type="text" placeholder="Name" formControlName = "name">
<button>Submit</button>
</form>How to add multiple FormControl
If you are familiar with reactive forms, adding a single form control to your reactive forms is very easy. Simply follow the steps mentioned above and attach multiple FormControls instead of just one.
app.component.ts file:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit{
constructor(private fb: FormBuilder){
}
myForm: FormGroup = new FormGroup({});
ngOnInit(): void {
this.myForm = this.fb.group({
'name': new FormControl(''),
'email': new FormControl(''),
'city': new FormControl(''),
'mobile': new FormControl(''),
});
}
}app.component.html file:
<form [formGroup] = "myForm">
<input type="text" formControlName = "name" placeholder="Name">
<input type="text" formControlName = "email" placeholder="Email">
<input type="text" formControlName = "city" placeholder="City">
<input type="text" formControlName = "mobile" placeholder="Mobile">
<button>Submit</button>
</form>How to use validators in Angular Reactive Form
Using validators in Angular reactive forms means applying validation rules to form controls. Angular offers built-in validators that can be used out of the box, and you can also create custom validators to meet specific needs.
Let's see the following code to understand how to use the built-in validators in Angular Reactive Forms.
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit{
constructor(private fb: FormBuilder){
}
myForm: FormGroup = new FormGroup({});
ngOnInit(): void {
this.myForm = this.fb.group({
'name': new FormControl('', [Validators.required, Validators.minLength(6)]),
'email': new FormControl('', [Validators.required, Validators.email]),
'city': new FormControl('', [Validators.required]),
'mobile': new FormControl('', [Validators.minLength(10), Validators.maxLength(10)]),
});
}
}Conclusion:
In conclusion, Angular's reactive forms offer a strong and valuable solution for building complex and dynamic forms in web applications.