Reactive Forms In Angular 11

Introduction

 
In this article, we will see Reactive Forms of angular. In this article, we will discuss how we can implement reactive forms in angular, how we can get input data, how to set validations and how we can set data in the input field.
 
 
In this article, 
  • Create angular project
  • Create a simple HTML form
  • Initialize Reactive Form
  • Get form data
  • Add validations
  • Set data in the form

Create Angular project

 
To create a new angular project run the following command in your command box. Here ReactiveForms is my project name. 
  1. Ng new ReactiveForms  

Create a simple HTML form

 
Create a form in your component file. Here I use bootstrap to design my input. I don’t know how to use bootstrap in angular please refer to this article.
 
In this form I used basic inputs like textbox, dropdown and radio button.
  1. <form class="p-5">    
  2.   <h1 class="text-success">Reactive Forms Demo</h1>    
  3.   <div class="form-row">    
  4.     <div class="form-group col-md-6">    
  5.       <label for="inputPassword4">Name</label>    
  6.       <input type="text" class="form-control" id="inputname4">    
  7.     </div>    
  8.     <div class="form-group col-md-6">    
  9.       <label for="inputEmail4">Email</label>    
  10.       <input type="email" class="form-control" id="inputEmail4">    
  11.     </div>    
  12.   </div>    
  13.   <div class="form-group col-6">    
  14.     <label for="inputAddress">Address</label>    
  15.     <input type="text" class="form-control" id="inputAddress" placeholder="1234 Main St">    
  16.   </div>    
  17.   <div class="form-group col-6">    
  18.     <label for="inputAddress2">Address 2</label>    
  19.     <input type="text" class="form-control" id="inputAddress2" placeholder="Apartment, studio, or floor">    
  20.   </div>    
  21.   <div class="form-row">    
  22.     <div class="form-group col-md-6">    
  23.       <label for="inputCity">City</label>    
  24.       <input type="text" class="form-control" id="inputCity">    
  25.     </div>    
  26.     <div class="form-group col-md-4">    
  27.       <label for="inputState">State</label>    
  28.       <select id="inputState" class="form-control">    
  29.         <option selected>Choose...</option>    
  30.         <option>Gujarat</option>    
  31.         <option>Panjab</option>    
  32.         <option>Tamilnadu</option>    
  33.         <option>Delhi</option>     
  34.       </select>    
  35.     </div>    
  36.     <div class="form-group col-md-2">    
  37.       <label for="inputZip">Zip</label>    
  38.       <input type="text" class="form-control" id="inputZip">    
  39.     </div>    
  40.   </div>    
  41.   <div class="form-group">    
  42.     <div class="form-check">    
  43.       <input class="form-check-input" type="checkbox" id="gridCheck">    
  44.       <label class="form-check-label" for="gridCheck">    
  45.         Married    
  46.       </label>    
  47.     </div>    
  48.   </div>    
  49.   <button type="button" class="btn btn-primary">Submit</button>    
  50. </form>    

Initialize Reactive Form

 
For making the form a reactive form you have to follow the below steps.
 
Step 1
 
Import FormsModule and ReactiveFormsModule in your import array of app.module.ts file.
  1. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { NgModule } from '@angular/core';  
  4.   
  5. import { AppRoutingModule } from './app-routing.module';  
  6. import { AppComponent } from './app.component';  
  7.   
  8. @NgModule({  
  9.   declarations: [  
  10.     AppComponent  
  11.   ],  
  12.   imports: [  
  13.     BrowserModule,  
  14.     AppRoutingModule,  
  15.   
  16.     //import this both module for use reactive form  
  17.     FormsModule,  
  18.     ReactiveFormsModule  
  19.   
  20.   
  21.   ],  
  22.   providers: [],  
  23.   bootstrap: [AppComponent]  
  24. })  
  25. export class AppModule { }  
Step 2
 
Create FormGroup object in your component.ts file.
 
Step 3
 
Define FormBuilder object in your constructor.
 
Step 4
 
Now initialize the form group with your expected fields as shown in the below code in your ngOnInit method or in your Constructor.
  1. import { Component } from '@angular/core';  
  2. import { FormBuilder, FormGroup } from '@angular/forms';  
  3.   
  4. @Component({  
  5.   selector: 'app-root',  
  6.   templateUrl: './app.component.html',  
  7.   styleUrls: ['./app.component.scss']  
  8. })  
  9. export class AppComponent {  
  10.   title = 'reactiveforms';  
  11.   
  12.   FormDemo: FormGroup;  
  13.   constructor(  
  14.     private fb: FormBuilder,  
  15.   ) {  
  16.   
  17.   
  18.   }  
  19.   
  20.   ngOnInit() {  
  21.     this.FormDemo = this.fb.group({  
  22.       name: [''],  
  23.       email: [''],  
  24.       address1: [''],  
  25.       address2: [''],  
  26.       city: [''],  
  27.       state: [],  
  28.       zip: [''],  
  29.       mstatus: [],  
  30.     });  
  31.   }  
  32. }  
Step 5
 
Now initialize form group to your form in component.html file and also add formControllName in input fields and initialize with your field name which you create in .ts file. You can initialize form group to form as shown the below image. While enter the value in the form control name add the same value as you define in your .ts file otherwise it gives an error.
 
  1. <form class="p-5" [formGroup]="FormDemo">    
  2.   <h1 class="text-success">Reactive Forms Demo</h1>    
  3.   <div class="form-row">    
  4.     <div class="form-group col-md-6">    
  5.       <label for="inputPassword4">Name</label>    
  6.       <input type="text" formControlName="name" class="form-control" id="inputname4">    
  7.     </div>    
  8.     <div class="form-group col-md-6">    
  9.       <label for="inputEmail4">Email</label>    
  10.       <input type="email" formControlName="email" class="form-control" id="inputEmail4">    
  11.     </div>    
  12.   </div>    
  13.   <div class="form-group col-6">    
  14.     <label for="inputAddress">Address</label>    
  15.     <input type="text" formControlName="address1" class="form-control" id="inputAddress" placeholder="1234 Main St">    
  16.   </div>    
  17.   <div class="form-group col-6">    
  18.     <label for="inputAddress2">Address 2</label>    
  19.     <input type="text" formControlName="address2" class="form-control" id="inputAddress2" placeholder="Apartment, studio, or floor">    
  20.   </div>    
  21.   <div class="form-row">    
  22.     <div class="form-group col-md-6">    
  23.       <label for="inputCity">City</label>    
  24.       <input type="text" formControlName="city" class="form-control" id="inputCity">    
  25.     </div>    
  26.     <div class="form-group col-md-4">    
  27.       <label for="inputState">State</label>    
  28.       <select id="inputState" formControlName="state" class="form-control">    
  29.         <option selected>Choose...</option>    
  30.         <option>Gujarat</option>    
  31.         <option>Panjab</option>    
  32.         <option>Tamilnadu</option>    
  33.         <option>Delhi</option>     
  34.       </select>    
  35.     </div>    
  36.     <div class="form-group col-md-2">    
  37.       <label for="inputZip">Zip</label>    
  38.       <input type="text" formControlName="zip" class="form-control" id="inputZip">    
  39.     </div>    
  40.   </div>    
  41.   <div class="form-group">    
  42.     <div class="form-check">    
  43.       <input class="form-check-input" type="checkbox" id="gridCheck" formControlName="mstatus">    
  44.       <label class="form-check-label" for="gridCheck" >    
  45.         Married    
  46.       </label>    
  47.     </div>    
  48.   </div>    
  49.   <button type="button" class="btn btn-primary">Submit</button>    
  50. </form>    

Get form data

 
You can easily get form data using the reactive form. You can get field value by the following the statement. 
  1. this.FormDemo.controls.name.value  
Here FormDemo is my FormGroup object and the name is my form field.
 
For making it simple or not write similar code repeatedly we can create a get method as shown below which return form.controls and after that, we can get field value from it.
 
In .ts File,
  1. get form() {  
  2.   return this.FormDemo.controls;  
  3. }  
  4.   
  5. submitForm(){  
  6.   console.log("Name :- "+this.form.name.value)  
  7.   console.log("Email :- "+this.form.email.value)  
  8.   console.log("Address1 :- "+this.form.address1.value)  
  9.   console.log("Address2 :- "+this.form.address2.value)  
  10.   console.log("City :- "+this.form.city.value)  
  11.   console.log("State :- "+this.form.state.value)  
  12.   console.log("Zip :- "+this.form.zip.value)   
  13.   console.log("Marital status :- "+this.form.mstatus.value)   
  14. }  
In html file, 
  1. <button type="button" (click)="submitForm()" class="btn btn-primary">Submit</button>  
Output
 
Forms Value
 
 
Console 
 
 

Add Validations in Form

 
In angular, there are different types of validator like required, email, min length, max length, etc.
 
But here we only user required an email validator to simply understand how validation works in angular.
 
Step 1
 
Define validator in your FormGroup initialization as show below.
  1. ngOnInit() {    
  2.     this.FormDemo = this.fb.group({    
  3.       name: ['',  [Validators.required]],    
  4.       email: ['', [Validators.required, Validators.email]],    
  5.       address1: [''  ,[Validators.required]],    
  6.       address2: ['',[Validators.required]],    
  7.       city: ['',[Validators.required]],    
  8.       state: ['',[Validators.required]],    
  9.       zip: ['',[Validators.required]],    
  10.       mstatus: [],    
  11.     });    
  12.   }    
Step 2
 
Check your form is valid or not in your submit method. You can check your form is valid or invalid by checking FormDemo.invalid.
 
Here FormDemo is formed group object and invalid is property of form group which returns true of your form is invalid. Return your method from further execution if your form is invalid.
 
Here also we initialize isSubmitted variable as true which we declare on top of constructor. 
  1. submitForm() {  
  2.     this.isSubmitted = true;  
  3.     if (this.FormDemo.invalid) {  
  4.       return  
  5.     }  
  6.     console.log("Name :- " + this.form.name.value)  
  7.     console.log("Email :- " + this.form.email.value)  
  8.     console.log("Address1 :- " + this.form.address1.value)  
  9.     console.log("Address2 :- " + this.form.address2.value)  
  10.     console.log("City :- " + this.form.city.value)  
  11.     console.log("State :- " + this.form.state.value)  
  12.     console.log("Zip :- " + this.form.zip.value)  
  13.     console.log("Marital status :- " + this.form.mstatus.value)  
  14.   }  
Step 3
 
Set error message as shown in the below image. Here we check the flag with isSubmitted because it does not check with this flag we will see an error message when your page is load and we don’t want that. We only want to show an error message when the user clicks in submit button.
 
 
The next thing we check here is form field has an error if the form field does not have any error then it’s time west to execute further.
 
Next, we create two labels with two different conditions which are if an email has required error then show required error message or email has invalid email error than show invalid email message.
  1. <form class="p-5" [formGroup]="FormDemo">    
  2.     
  3.   <h1 class="text-success">Reactive Forms Demo</h1>    
  4.   <div class="form-row">    
  5.     <div class="form-group col-md-6">    
  6.       <label for="inputPassword4">Name</label>    
  7.       <input type="text" formControlName="name" class="form-control" id="inputname4">    
  8.       <div *ngIf="isSubmitted&&form.name.errors" class="text-danger">    
  9.         <p *ngIf="form.name.errors.required">Please enter name.</p>    
  10.       </div>    
  11.     </div>    
  12.     <div class="form-group col-md-6">    
  13.       <label for="inputEmail4">Email</label>    
  14.       <input type="email" formControlName="email" class="form-control" id="inputEmail4">    
  15.       <div *ngIf="isSubmitted&&form.email.errors" class="text-danger">    
  16.         <p *ngIf="form.email.errors.required">Please enter email.</p>    
  17.         <p *ngIf="form.email.errors.email">Please enter valid email.</p>    
  18.       </div>    
  19.     </div>    
  20.   </div>    
  21.   <div class="form-group col-6">    
  22.     <label for="inputAddress">Address</label>    
  23.     <input type="text" formControlName="address1" class="form-control" id="inputAddress" placeholder="1234 Main St">    
  24.     <div *ngIf="isSubmitted&&form.address1.errors" class="text-danger">    
  25.       <p *ngIf="form.address1.errors.required">Please enter Address.</p>    
  26.     </div>    
  27.   </div>    
  28.   <div class="form-group col-6">    
  29.     <label for="inputAddress2">Address 2</label>    
  30.     <input type="text" formControlName="address2" class="form-control" id="inputAddress2"    
  31.       placeholder="Apartment, studio, or floor">    
  32.       <div *ngIf="isSubmitted&&form.address2.errors" class="text-danger">    
  33.         <p *ngIf="form.address2.errors.required">Please enter Address2.</p>    
  34.       </div>    
  35.   </div>    
  36.   <div class="form-row">    
  37.     <div class="form-group col-md-6">    
  38.       <label for="inputCity">City</label>    
  39.       <input type="text" formControlName="city" class="form-control" id="inputCity">    
  40.       <div *ngIf="isSubmitted&&form.city.errors" class="text-danger">    
  41.         <p *ngIf="form.city.errors.required">Please enter city.</p>    
  42.       </div>    
  43.     </div>    
  44.     <div class="form-group col-md-4">    
  45.       <label for="inputState">State</label>    
  46.       <select id="inputState" formControlName="state" class="form-control">    
  47.         <option selected>Choose...</option>    
  48.         <option>Gujarat</option>    
  49.         <option>Panjab</option>    
  50.         <option>Tamilnadu</option>    
  51.         <option>Delhi</option>    
  52.       </select>    
  53.       <div *ngIf="isSubmitted&&form.state.errors" class="text-danger">    
  54.         <p *ngIf="form.state.errors.required">Please enter state.</p>    
  55.       </div>    
  56.     </div>    
  57.     <div class="form-group col-md-2">    
  58.       <label for="inputZip">Zip</label>    
  59.       <input type="text" formControlName="zip" class="form-control" id="inputZip">    
  60.       <div *ngIf="isSubmitted&&form.zip.errors" class="text-danger">    
  61.         <p *ngIf="form.zip.errors.required">Please enter zip code.</p>    
  62.       </div>    
  63.     </div>    
  64.   </div>    
  65.   <div class="form-group">    
  66.     <div class="form-check">    
  67.       <input class="form-check-input" type="checkbox" id="gridCheck" formControlName="mstatus">    
  68.       <label class="form-check-label" for="gridCheck">    
  69.         Married    
  70.       </label>    
  71.            
  72.     </div>    
  73.   </div>    
  74.   <button type="button" (click)="submitForm()" class="btn btn-primary">Submit</button>    
  75. </form>    
Output
 
Required Validation
 
 
Email Validation 
 

Set data in the form

 
Set value in form is also easy as to get value from the form.
 
Here we add a button in the HTML file on that button click we want to set data in the form.
  1. <button class="btn btn-warning" type="button" (click)="setDataInForm()">Set Data In Form</button>  
Create method in component.ts file for set data in your form field as show in below.
  1. setDataInForm(){  
  2.   this.form.name.setValue("Yogesh");  
  3.   this.form.email.setValue("[email protected]");  
  4.   this.form.address1.setValue("Abc Street");  
  5.   this.form.address2.setValue("Abc steet 2");  
  6.   this.form.city.setValue("Ahmedabad");  
  7.   this.form.state.setValue("Gujarat");  
  8.   this.form.zip.setValue("123456");  
  9.   this.form.mstatus.setValue(true);  
  10. }  
Output 
 
 
I hope you find this article helpful and get information from it. If you like this article kindly share it with your friends and family.


Similar Articles