In order to effectively utilize FormArray, it is important to grasp the following concepts:
Mandatory form group
\/\/\/
<form [formGroup]="categories">
<input type="text" placeholder="category_name" formControlName="category_name" />
Define form array
\/\/\/
<div formArrayName="itemsList" *ngFor="let item of categories.get('itemsList').controls; let i = index;">
<div [formGroupName]="i"> <-- crucial step
<input type="text" placeholder="item_id" formControlName="item_id" />
<input type="text" placeholder="Item Name" formControlName="item_name" />
<input type="text" placeholder="Quantity" formControlName="quantity" />
</div>
</div>
</form>
To implement the above HTML structure in your TypeScript file, ensure you have:
categories: FormGroup;
itemsList: FormArray;
this.categories = this._formBuilder.group({
category_name: [null, Validators.compose([Validators.required, Validators.minLength(5)])],
itemsList: this._formBuilder.array([
this._formBuilder.group({
item_id: 0,
item_name: '',
quantity: 0,
})
])
});
Lastly, create an addNew function:
addItem() {
this.itemsList = this.categories.get('itemsList') as FormArray;
this.itemsList.push(this.itemsList);
}