What is an Angular Form Array?
In Angular Reactive Forms, A Form Array is a dynamic form where form controls are added or removed to the form by the user on run time.
Why is Angular Form Array needed?
Normal Form in Angular Reactive Forms is a static form with a pre-defined number of fields like form controls, their initial values, and form validation rules, and give property names for each field of the form. So If we need to add dynamic fields then we need an Angular Form Array.
Declare FormArray into app.componnet.ts file
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
Bind the hotelForm in app.component.ts file
create the hotelForm and defined the fields hotel_name, hotel_phonenum and dishVarieties defined as a form Array.
hotelForm!: FormGroup;
ngOnInit() : void{
this.hotelForm = this.fb.group({
hotel_name: '',
hotel_phonenum: '',
dishVarieties: this.fb.array([])
});
}
Now, a get method dishVarieties, which returns the dishVarieties FormArray from the hotelForm
get dishVarieties() : FormArray {
return this.hotelForm.controls["dishVarieties"] as FormArray
}
newDish Form Group
We created two fields under each new dish like dish_name and dish_cost. Hence we created a FormGroup with two fields. The method newDish creates a new FormGroup and returns it.
newDish(): FormGroup {
return this.fb.group({
dish_name: '',
dish_cost: '',
})
}
Add dish dynamically
Now, we will add a new dish to the dishVarieties FormArray. Since it is an array we can use the push method to add the new dish using the the addDish() method.
addDish() {
this.dishVarieties.push(this.newDish());
}
Note:- addDish() method returns a FormGroup. The name of the FormGroup is its Index in the FormArray.
Remove dish dynamically
Now, we will remove a dish through the removeAt method from the dishVarieties FromArray.
removeDish(i:number) {
this.dishVarieties.removeAt(i);
}
Now, add the complete code to the app.component.html file.
<div class="text-align-center col-sm-6" align="center">
<h2>Add Hotel Details</h2>
<form [formGroup]="hotelForm" id="userId">
<div class="row col-sm-12" style="padding-bottom:10px">
<div class="col-sm-4 float-left"><label>Name:</label> </div>
<div class="col-sm-8"><input type="text" formControlName="hotel_name" /></div>
</div>
<div class="row col-sm-12" style="padding-bottom:10px">
<div class="col-sm-4 float-left"><label>Phone:</label> </div>
<div class="col-sm-8"><input type="text" formControlName="hotel_phonenum" /></div>
</div>
<div formArrayName="dishVarieties">
<div *ngFor="let dishVariety of dishVarieties.controls; let i=index">
<div class="row col-sm-12" style="padding-bottom:10px" [formGroupName]="i">
<label>Dish Name :</label>
<input type="text" formControlName="dish_name" style="width:100px;">
<label style="padding-left:10px">Dish Cost:</label>
<input type="text" formControlName="dish_cost" style="width:50px;">
<button (click)="removeDish(i)" class="btn1 btn-primary">Remove</button>
</div>
</div>
</div>
<div class="row col-sm-12" style="padding-bottom:10px">
<div class="col-sm-4 float-left"></div>
<div class="col-sm-8">
<input type="submit" class="btn btn-primary" name="userSub" (click)="addDish()" value="Add Dish with Cost" />
</div>
</div>
<div class="row">
<input type="submit" class="btn btn-primary" (click)="Submit()" name="userSub" value="Submit" />
</div>
</form>
</div>
Now, add the source code to the app.component.ts file
import { Component, OnInit} from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
hotelForm!: FormGroup;
constructor(private fb:FormBuilder){
}
ngOnInit() : void{
this.hotelForm = this.fb.group({
hotel_name: '',
hotel_phonenum: '',
dishVarieties: this.fb.array([])
});
}
get dishVarieties() : FormArray {
return this.hotelForm.controls["dishVarieties"] as FormArray
}
newDish(): FormGroup {
return this.fb.group({
dish_name: '',
dish_cost: '',
})
}
addDish() {
this.dishVarieties.push(this.newDish());
}
removeDish(i:number) {
this.dishVarieties.removeAt(i);
}
Submit(){
console.log(this.hotelForm.value);
}
}
Now, fill the details into the form and add the Dishes “Dal Makhni” and “Sahi Paneer” along with the price.
After that click on the Submit button and check the output on the browser console.
Remove Dish “Dal Makhni” from the Dish items
after that click on the Submit button and check the output on the browser console.