How to Add and Remove Row Dynamically in Angular with Validations :  Angular is an open-source, JavaScript system written in TypeScript. Google keeps up with it, and its main role is to foster single-page applications. As a system, Angular enjoys clear benefits while additionally giving a standard construction to engineers to work with. It empowers clients to make enormous applications in a viable way.

JavaScript is the most ordinarily utilized customer side prearranging language. It is composed into HTML reports to empower collaborations with website pages from various perspectives. As a generally simple to-learn language with inescapable help, it is appropriate to foster current applications.

However, is JavaScript ideal for creating single-page applications that require particularity, testability, and designer efficiency? Maybe not.

Requirments

Basic knowledge of Angular

Any Editor such as Visual Studio Code

External Library Added :

Bootstrap

FontAwesome

Introduction to the Blog

This tutorial will teach you how to add and remove rows from the grid.
This tutorial also covers the Reactive form validations on dynamically generated elements and reset form after submitting the form.

After Researching many things over google about this functionality the blogs were not covering all things at once.

So I decided to write code myself and share it with everyone who really needs it.

Let’s start :

It will require 3 Files.

app.component.html

app.component.ts

style.css (to import FontAwesome and Bootstrap library ).


.app.component.html

<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Dynamic Add and Remove Rows</h4>
<form [formGroup]="requestCreateForm" (ngSubmit)="submit()" class="row">
<div class="col-lg-12">
<hr>
<!--  Just a Divider Line -->
</div>
<div class="col-lg-12" formArrayName="itemRows">
<div class="row" *ngFor="let itemrow of itemRowsControls; let i=index" [formGroupName]="i">
<label class="col-lg-1 col-form-label">Currency
<span class="text-danger">*</span>
</label>
<div class="col-lg-2">
<select class="form-control" formControlName="currency" [ngClass]="{ 'is-invalid': submitted && itemrow.get( 'currency')?.errors}">
<option value="">Select</option>                                      
<option value="INR ">INR</option>
<option value="Doller ">DOLLER</option>
</select>

<div *ngIf="submitted && itemrow.get( 'currency')?.errors " class="invalid-feedback ">
<div *ngIf="submitted && itemrow.get( 'currency')?.errors?.required ">
Currency is required.
</div>
</div>
</div>
<label for="amt-input " class="col-lg-1 col-form-label ">Amount <span class="text-danger ">*</span>
</label>
<div class="col-md-2 pr-0 mb-3 ">
<input class="form-control" formControlName="amount" type="text " id="amt-input " [ngClass]="{ 'is-invalid': submitted && itemrow.get( 'amount')?.errors}" />
<div *ngIf="submitted && itemrow.get( 'amount')?.errors" class="invalid-feedback ">
<div *ngIf="submitted && itemrow.get( 'amount')?.errors?.required">
Amount is required.
</div>
<div *ngIf="submitted && itemrow.get('amount')?.hasError( 'maxlength') ">
Amount can not exceed 10 characters in length.
</div>
<div *ngIf="submitted && itemrow.get('amount')?.errors?.pattern">
Amount Number must be number
</div>
</div>
</div>
<div class="col-lg-2 ">
<label class="col-form-label ">Currency Type<span class="text-danger ">*</span></label>
</div>
<div class="col-md-2 pr-0 mb-3 ">
<select class="form-control " formControlName="currencyType" [ngClass]="{ 'is-invalid': submitted && itemrow.get( 'currencyType')?.errors}">
<option value=" ">Select</option>
<option value="Fake ">Fake </option>
<option value="Original ">Original</option>
</select>
<div *ngIf="submitted && itemrow.get('currencyType')?.errors" class="invalid-feedback">
<div *ngIf="submitted && itemrow.get('currencyType')?.errors?.required">
Type is required.
</div>
</div>
</div>
<div class="col-lg-2 text-right">
<button type="button" (click)="addNewRow()" class="btn btn-primary mr-2"><i class="fa fa-plus-circle"
aria-hidden="true"></i></button>
<button type="button" (click)="deleteRow(i)" class="btn btn-outline-danger ml-2"><i class="fa fa-times" aria-hidden="true"></i></button>
</div>
</div>
</div>
<div class="col-lg-12">
<hr>
</div>
<div class="col-lg-12 text-center mt-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
<!-- end col -->
</div>
<!-- end row -->
</div>

 


.app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from "@angular/forms";
import { Router } from "@angular/router";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
submitted = false;
requestCreateForm: FormGroup;
TotalRow : number;
constructor(private formBuilder: FormBuilder,private router: Router,) { }
get f(){
return this.requestCreateForm.controls;
}
get t() { return this.f.itemRows as FormArray; }
get itemRowsControls() { return (<FormArray>this.requestCreateForm.get('itemRows')).controls; }
ngOnInit(): void {
this.requestCreateForm = this.formBuilder.group({
itemRows: this.formBuilder.array([this.initItemRows()]),      
});     
}
initItemRows() {
return this.formBuilder.group({
currency: ['', Validators.compose([Validators.required])],
amount: ['', Validators.compose([Validators.required,  Validators.pattern("^[0-9]*$"),Validators.maxLength(10)])],
currencyType: ['', Validators.compose([Validators.required])],
});
}
addNewRow() {     
const control = <FormArray>this.requestCreateForm.controls['itemRows'];
if(control.length <= 4){        
control.push(this.initItemRows());    
}
else{
alert('Sorry !! You can only add 5 Rows');
}

}
deleteRow(index: number) {
const control = <FormArray>this.requestCreateForm.controls['itemRows'];
if(control != null){
this.TotalRow = control.value.length ;
}
if(this.TotalRow > 1){
control.removeAt(index);
}    
else{
alert('Last Row can not be deleted');
}

}  
emptyArray(){
// Removing all valus from array expect [0] index ; 
const control = <FormArray>this.requestCreateForm.controls['itemRows'];
this.TotalRow = control.value.length  - 1;
for (let i = this.TotalRow - 1; i >= 0; i--){
control.removeAt(i);
}   
}
submit(){
this.submitted = true;
console.log('This is formdata-->', this.requestCreateForm.value);
if (this.requestCreateForm.invalid) {
alert('Form is not Valid Now');
return;
}
else{
alert('A Valid Form');
this.submitted = false; 
this.requestCreateForm.reset();
this.t.reset(); 
}

}
}

 


style.css

@import "~bootstrap/dist/css/bootstrap.min.css";
@import "~font-awesome/css/font-awesome.css";

 

To clone this project

git clone https://github.com/rohitgautam-mobi/Add-and-Remove-Row-Dynamically-in-Angular-with-Validations.git

 

That is all for this blog

Thanks 🙂

Happy Coding

Please follow and like us: