Creating Table With Reactive Forms In Angular 9 Using PrimeNg Table

Angular provides two approaches for defining our views; i.e. ,Template-Driven Forms & Reactive Forms. Template driven forms give you more control over designing your HTML, but at the same time it has a drawback in that view is heavily loaded with HTML Content. In contrast,  Reactive Forms provides you with an approach to define your HTML Form with all its validation logic inside your Component making your views (HTML) a lot more readable. Since your view creation logic is inside Component you can actually do programming on it when required.
In this article we’ll try to create a use case wherein, we’ll allow Admins of the portal to create new employee records in the System & when we click on the Save it will be actually saved to the Database. For adding a new empty row to the Table I’ve provided a AddRow button which adds an empty Row to the PrimeNg Turbo Table, with an option of deleting any row. To create the sample project I've used Angular 9 Reactive forms & PrimeNg turbo table. So let’s start with coding our sample project. I’ve installed the pre-requisite libraries such as PrimeNg, FontAwesome & Bootstrap in my project & added the reference in angular.json file. Here is the code snippet for the same.
  1. "styles": [  
  2.    "node_modules/bootstrap/dist/css/bootstrap.min.css",  
  3.    "node_modules/font-awesome/css/font-awesome.min.css",  
  4.    "node_modules/primeng/resources/themes/rhea/theme.css",  
  5.    "node_modules/primeng/resources/primeng.min.css",  
  6.    "src/styles.css"  
  7. ]   
I’ve added a new component, add-employee, to our application using the angular/cli & referred it in our app.component HTML file using the add-employee component selector.
Here is the code snippet for our add-employee component ts file. We started off by defining our FromGroup for the HTML Page inside add-employee.component.ts file:
  1. employeeForm: FormGroup;  
  2. columns:string[]; // priming turbo table columns  
Inside the constructor I’ve initialized the columns array with some 4 columns i..e:
  1. this.columns = ["Name""Address""Salary""IsActive""Delete"];  
Our reactive form HTML creation logic comes inside the ngOnInit method wherein we called the createForm() method which actually does the work of initializing the employeeForm & adding a blank empty row to the Table as a FormGroup. Now using ReactiveForms we are trying to build a table, which basically will have one or more rows, so for defining the tableRows I’d used FormGroupArray. Here is the code snippet performing the same.
  1. /** 
  2.  * Initializes the Form & by default adds an empty row to the PRIMENG TABLE 
  3.  */  
  4. private createForm(): void {  
  5.     this.employeeForm ={  
  6.         //tableRowArray is a FormArray which holds a list of FormGroups  
  7.         tableRowArray: this.formBuilder.array([  
  8.             this.createTableRow()  
  9.         ])  
  10.     })  
  11. }  
Here is the code snippet for CreateTableRow() which provides a controls for each table row cell, as we only have 4 columns; i.e., Name, Address, Salary & IsActive. Below method creates this using the FormControl class.
  1. /** 
  2.  * Returns the FormGroup as a Table Row 
  3.  */  
  4. private createTableRow(): FormGroup {  
  5.     return{  
  6.         name: new FormControl(null, {  
  7.             validators: [Validators.required, Validators.minLength(3), Validators.maxLength(50)]  
  8.         }),  
  9.         address: new FormControl(null, {  
  10.             validators: [Validators.required, Validators.maxLength(500)]  
  11.         }),  
  12.         salary: new FormControl(null, {  
  13.             validators: [Validators.required, Validators.pattern(/^\d{1,6}(?:\.\d{0,2})?$/), Validators.minLength(3), Validators.maxLength(50)]  
  14.         }),  
  15.         isActive: new FormControl({  
  16.             value: true,  
  17.             disabled: true  
  18.         })  
  19.     });  
  20. }  
You can explicitly enable or disable a control like we did for isActive column case, provide a default value of true to it & also disabled the control.

To get the FormGroupArray I’ve defined a getter method which returns the FormArray from the tableRowArray.
  1. get tableRowArray(): FormArray {  
  2.    return this.employeeForm.get('tableRowArray') as FormArray;  
  3. }  
For adding new empty row to the table I’ve created a method which adds a new FormGroup by using createNewRow() in tableRowArray FormArray.
  1. addNewRow(): void {  
  2.    this.tableRowArray.push(this.createTableRow());  
  3. }  
Similarly for deleting the existing row I’ve defined OnDeleteRow method which take Rowindex & accordingly removes that row from our tableRowArray FormArray.
  1. onDeleteRow(rowIndex:number): void {  
  2.    this.tableRowArray.removeAt(rowIndex);  
  3. }  
Now let’s move our attention towards our HTML add-employee.component.html. I’ve defined our HTML form using the form tag, remember the employeeForm which we created in our TS file.
  1. <form [formGroup]="employeeForm">  
Inside this form tag we defined our PrimeNg Turbo Table using the p-table tag.
  1. <p-table [value]="tableRowArray.controls" [responsive]="true">  
  2.     <ng-template pTemplate="header">  
  3.         <tr>  
  4.             <ng-container *ngFor="let col of columns">  
  5.                 <td>{{col}}</td>  
  6.             </ng-container>  
  7.         </tr>  
  8.     </ng-template>  
Now let’s define the template for our Body wherein we’ll actually use the tableRowArray FormArray we created in our TS file.
  1. <ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex">  
  2.     <ng-container formArrayName="tableRowArray">  
  3.         <tr [formGroupName]="rowIndex">  
  4.             <td>  
  5.                 <input type="text" class="form-control form-control-sm" formControlName="name" />  
  6.                 <div class="text-danger" *ngIf="rowData.get('name').errors && (rowData.get('name').dirty || rowData.get('name').touched)">  
  7.                     <div *ngIf="rowData.get('name').errors?.required">Name is Required</div>  
  8.                 </div>  
  9.             </td>  
  10.             <td>  
  11.                 <input type="text" class="form-control form-control-sm" formControlName="address" />  
  12.                 <div class="text-danger" *ngIf="rowData.get('address').errors && (rowData.get('address').dirty || rowData.get('address').touched)">  
  13.                     <div *ngIf="rowData.get('address').errors?.required">Address is Required</div>  
  14.                 </div>  
  15.             </td>  
  16.             <td>  
  17.                 <input type="text" class="form-control form-control-sm" formControlName="salary" />  
  18.                 <div class="text-danger" *ngIf="rowData.get('salary').errors && (rowData.get('salary').dirty || rowData.get('salary').touched)">  
  19.                     <div *ngIf="rowData.get('salary').errors?.required">Salary is Required</div>  
  20.                     <div *ngIf="rowData.get('salary').errors?.pattern">Number Only, max 6 digits with max 2 decimals</div>  
  21.                 </div>  
  22.             </td>  
  23.             <td>  
  24.                 <div class="form-check">  
  25.                     <input type="checkbox" class="form-check-input" formControlName="isActive" />  
  26.                     <label class="form-check-label"></label>  
  27.                 </div>  
  28.             </td>  
  29.             <td>  
  30.                 <button type="button" class="btn btn-default" title="Delete" (click)="onDeleteRow(rowIndex)">  
  31.                     <i class="fa fa-trash-o" aria-hidden="true"></i>  
  32.                 </button>  
  33.             </td>  
  34.         </tr>  
  35.     </ng-container>  
  36. </ng-template>  
For allowing the user to add new blank rows to the table we provide the user with Add Row button, here is the code snippet for the same.
  1. <div class="card-footer">  
  2.    <button type="button" class="btn btn-primary btn-sm pull-left" (click)="addNewRow()">Add Row</button>  
  3.    <button type="button" class="btn btn-success btn-sm pull-right" title="Save">Save</button>  
  4. </div>  
Here is the full code snippet for the add-employee.component.html file
  1. <div class="card">  
  2.     <div class="card-header">  
  3.         <h5>Reactive Forms with PrimeNg Table</h5>  
  4.     </div>  
  5.     <div class="card-body">  
  6.         <form [formGroup]="employeeForm">  
  7.             <p-table [value]="tableRowArray.controls" [responsive]="true">  
  8.                 <ng-template pTemplate="header">  
  9.                     <tr>  
  10.                         <ng-container *ngFor="let col of columns">  
  11.                             <td>{{col}}</td>  
  12.                         </ng-container>  
  13.                     </tr>  
  14.                 </ng-template>  
  15.                 <ng-template pTemplate="body" let-rowData let-rowIndex="rowIndex">  
  16.                     <ng-container formArrayName="tableRowArray">  
  17.                         <tr [formGroupName]="rowIndex">  
  18.                             <td>  
  19.                                 <input type="text" class="form-control form-control-sm" formControlName="name" />  
  20.                                 <div class="text-danger" *ngIf="rowData.get('name').errors && (rowData.get('name').dirty || rowData.get('name').touched)">  
  21.                                     <div *ngIf="rowData.get('name').errors?.required">Name is Required</div>  
  22.                                 </div>  
  23.                             </td>  
  24.                             <td>  
  25.                                 <input type="text" class="form-control form-control-sm" formControlName="address" />  
  26.                                 <div class="text-danger" *ngIf="rowData.get('address').errors && (rowData.get('address').dirty || rowData.get('address').touched)">  
  27.                                     <div *ngIf="rowData.get('address').errors?.required">Address is Required</div>  
  28.                                 </div>  
  29.                             </td>  
  30.                             <td>  
  31.                                 <input type="text" class="form-control form-control-sm" formControlName="salary" />  
  32.                                 <div class="text-danger" *ngIf="rowData.get('salary').errors && (rowData.get('salary').dirty || rowData.get('salary').touched)">  
  33.                                     <div *ngIf="rowData.get('salary').errors?.required">Salary is Required</div>  
  34.                                     <div *ngIf="rowData.get('salary').errors?.pattern">Number Only, max 6 digits with max 2 decimals</div>  
  35.                                 </div>  
  36.                             </td>  
  37.                             <td>  
  38.                                 <div class="form-check">  
  39.                                     <input type="checkbox" class="form-check-input" formControlName="isActive" />  
  40.                                     <label class="form-check-label"></label>  
  41.                                 </div>  
  42.                             </td>  
  43.                             <td>  
  44.                                 <button type="button" class="btn btn-default" title="Delete" (click)="onDeleteRow(rowIndex)">  
  45.                                     <i class="fa fa-trash-o" aria-hidden="true"></i>  
  46.                                 </button>  
  47.                             </td>  
  48.                         </tr>  
  49.                     </ng-container>  
  50.                 </ng-template>  
  51.             </p-table>  
  52.         </form>  
  53.     </div>  
  54.     <div class="card-footer">  
  55.         <button type="button" class="btn btn-primary btn-sm pull-left" (click)="addNewRow()">Add Row</button>  
  56.         <button type="button" class="btn btn-success btn-sm pull-right" title="Save">Save</button>  
  57.     </div>  
  58. </div>  
Now run the application & try playing with Adding a new blank row, deleting the row or with validations. Below is the snapshot for the same.