How To Insert Multiple Data Using Reactive Form In Angular 7

Introduction

 
Recently, I was working on a project with Angular Reactive Forms. We had one requirement of inserting multiple data in a single batch using FormGroup, FormBuilder, and FormArray.
 
There may be several approaches to this. This is just one of them that I am using. 
 
Prerequisites
  • Basic Knowledge of Angular version 2 and higher.
  • Basic Knowledge of HTML.
  • Basic Knowledge of Reactive Forms.

How to achieve this

 
Let’s start from the beginning to create a demo application.
 
Step 1
 
Open the Command Prompt and write the command for creating a new Angular project. Say, our project name is AngularMultipleData.
 
ng new projectname
 
How To Insert Multiple Data Using Reactive Form Angular 7 
 
Step 2
 
The application is created successfully. Now, open your project in Visual Studio Code or you can simply open it using the command given below.
 
code .
 
How To Insert Multiple Data Using Reactive Form Angular 7 
 
Open VS Code Explorer for viewing the application structure.
 
How To Insert Multiple Data Using Reactive Form Angular 7 
 
Step 3 
 
After the application opens in Visual Studio, open the app.module.ts file and import FormsModule and ReactiveFormsModule from @angular/forms.
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { AppComponent } from './app.component';  
  4.   
  5. import {FormsModule,ReactiveFormsModule} from '@angular/forms'  
  6.   
  7.   
  8. @NgModule({  
  9.   declarations: [  
  10.     AppComponent  
  11.   ],  
  12.   imports: [  
  13.     BrowserModule,  
  14.     FormsModule,  
  15.     ReactiveFormsModule   
  16.   ],  
  17.   providers: [],  
  18.   bootstrap: [AppComponent]  
  19. })  
  20.   
  21. export class AppModule { }  

Step 4
 
Now, open the app.component.ts file. Here we need to import FormBuilder and FormGroup from @angular/forms.

  1. import {FormBuilder,FormGroup } from  '@angular/forms';  

Step 5
 
Create a reactive form object with a name, say, SchoolDetailsForm and create an instance of FormBuilder in the constructor.
  1. SchoolDetailsForm : FormGroup;  
  2. constructor(private fb :FormBuilder)  
  3. {   
  4. }   
Step 6
 
Create a JSON object with basic data. This object holds the key value pair data. We use this data with *ngFor directive in the HTML template.
  1. AllClassData=[  
  2.     {  
  3.     'className':'5th'  
  4.     },  
  5.    {  
  6.     'className':'8th'  
  7.    },  
  8.    {  
  9.     'className':'10th'  
  10.     },  
  11.    {  
  12.     'className':'12th'  
  13.    },  
  14. ]  
Step 7
 
Now, create a function for our Reactive form with formGroup and formControl. The For loop helps us to push the array and dynamically build the formGroup.
 
The code snippet for that is given below.
  1. createform()  
  2. {  
  3.   let arr=[];  
  4.   for(let i=0;i< this.AllClassData.length;i++)  
  5.   {     
  6.     arr.push(this.BuildFormDynamic(this.AllClassData[i]))  
  7.      
  8.   }  
  9.     this.SchoolDetailsForm =  this.fb.group({  
  10.       SchoolName : [''],  
  11.       ClassDetails:this.fb.array(arr)  
  12.     })  
  13. }  
Step 8
 
Now, create one more function that returns the formGroup with fields like TotalStudent, Grade total, and Class. The code for this is given below. 
  1. BuildFormDynamic(ClassDatas):FormGroup{  
  2.  return this.fb.group({  
  3.        Class:[ClassDatas.className],  
  4.        TotalStudent:[''],  
  5.        GradeAStudent:[''],  
  6.        GradeBStudent :['']  
  7.   })  
  8. }  
Step 9
 
The code of our app.component.ts file is given below. We have created a Save button-click event for the console data.
  1. import { Component , OnInit} 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.css']    
  8. })    
  9. export class AppComponent implements OnInit {    
  10.   title = 'AngularMultipleData';    
  11.   SchoolDetailsForm : FormGroup;    
  12.     
  13.   AllClassData=[    
  14.     {    
  15.     'className':'5th'    
  16.     },    
  17.    {    
  18.     'className':'8th'    
  19.    },    
  20.    {    
  21.     'className':'10th'    
  22.     },    
  23.    {    
  24.     'className':'12th'    
  25.    },    
  26. ]    
  27.   constructor(private fb :FormBuilder)    
  28.   {    
  29.         
  30.   }    
  31.   ngOnInit()    
  32.   {    
  33.         
  34.     this.createform();    
  35.   }    

  36. createform()    
  37. {    
  38.   let arr=[];    
  39.   for(let i=0;i< this.AllClassData.length;i++)    
  40.   {       
  41.     arr.push(this.BuildFormDynamic(this.AllClassData[i]))    
  42.        
  43.   }    

  44.     this.SchoolDetailsForm =  this.fb.group({    
  45.       SchoolName : [''],    
  46.       ClassDetails:this.fb.array(arr)    
  47.     })    
  48. }  
  49.     
  50. BuildFormDynamic(product):FormGroup{    
  51.  return this.fb.group({    
  52.        Class:[product.className],    
  53.        TotalStudent:[''],    
  54.        GradeAStudent:[''],    
  55.        GradeBStudent :['']    
  56.   })    
  57. }    
  58.     
  59.   SaveData()    
  60.   {    
  61.     console.log(this.SchoolDetailsForm.value);    
  62.     //pass this data to service and api node/webapi  
  63.   
  64.   }    
  65. }    

Step 10

Now, open the app.component.html file and write the following code. We used *ngFor directive for iterating the data and finding the controls of our Reactive form.
  1. <div>  
  2.     <form [formGroup]="SchoolDetailsForm" (submit)="SaveData()">  
  3.         <table>  
  4.             <tr>  
  5.                 <td>  
  6.                     <b>School Name</b>  
  7.                 </td>  
  8.                 <td>  
  9.                     <input  type="text" formControlName="SchoolName" />  
  10.                 </td>  
  11.             </tr>  
  12.         </table>  
  13.         <br/>  
  14.         <table>  
  15.             <tr formArrayName="ClassDetails" *ngFor="let cd of SchoolDetailsForm.controls.ClassDetails.controls ;let i=index;">  
  16.                 <td formGroupName={{i}}>  
  17.                     <b>   
  18.       Class {{cd.get('Class').value}}  
  19.      </b>  
  20.                     <input  type="text" formControlName="TotalStudent" placeholder="Total Student" />  
  21.                     <input  type="text" formControlName="GradeAStudent" placeholder="Total Grade A Student" />  
  22.                     <input  type="text" formControlName="GradeBStudent" placeholder="Total Grade B Student" />  
  23.                 </td>  
  24.             </tr>  
  25.             <tr>  
  26.                 <td>  
  27.                     <input type="submit" value="Click Me" />  
  28.                 </td>  
  29.             </tr>  
  30.         </table>  
  31.     </form>  
  32. </div>    
Step 11
 
Now, run the application using the following commands and open it in the Chrome broswer at port number 4200. You can see our data with fields in the console. You can pass this JSON object to the Node API or WebAPI and insert into our database. The output is shown in the following image.
 
ng serve or ng s -o 
 
How To Insert Multiple Data Using Reactive Form Angular 7 
I have attached the .rar file of this demonstration. If you want the code of this application, please download it.

Summary


In this article, we learned how to insert multiple data using Reactive Forms in Angular. I hope you enjoyed this article and learned the process. Thank you for reading.

If you have any questions/feedback, please write in the comment box.


Similar Articles