Spent almost a day now and learned a lot about Angular Reactive forms but still my question unanswered I am simply building a list of items with edit button on each items. Once edit button clicked that item name and description will be able to edit and submit. Simple and works fine. Now I want to add sub item to that item so I have add button which will add form array to that item form group and add sub item. That works but problem is when I click on other Item same subItem is added there too. Looks like I am not specifically adding sub item to the item which I click the edit button on. Here how I am adding sub item
buildItemsForm() {
this.itemForm = this.fb.group({
Description: [''],
ItemCode: ['']
Variations: this.fb.array([])
});
}
addVariationToItem() {
const variationsControl = this.itemForm.get('Variations') as FormArray; // here i need to specify the specific item
variationsControl.push(this.itemVariation());
}
itemVariation() {
return this.fb.group({
color: ['']
})}
This is the result
{
Description: 'this is description'
ItemCode: '123'
Variations:[
color:'red' ] // Added Here
}
{
Description: 'this is description2'
ItemCode: '789'
Variations:[
color:'red' ] // But Adding it here too
}
Update: Here is the html. I am getting items from backend response which is looped to render list of items then within the items each form is rendered so I don't think I need to change my top form to FromArray unless I have design my code wrong.
<div *ngFor="let item of items; let i = index" class="card">
<div class="item-info" *ngIf="!closeInEditItem(item)">
<div>Description : {{item.Description}}</div>
<div>Item Code : {{item.ItemCode}}</div>
<div>Variation:</div>
<button (click)="editItem(item)">Edit</button></div>
<div class="form-group" *ngIf="editSate && itemToEdit.Id == item.Id">
<form (ngSubmit)="updateItem(item)" [formGroup]="itemForm">
<textarea matInput type="text" class="form-control" placeholder="Edit Description"
formControlName="Description"></textarea>
<input matInput type="text" class="form-control" placeholder="Edit Item Code" formControlName="ItemCode">
<div formArrayName="Variations">
<div *ngFor="let variationItem of itemForm.controls['Variations'].controls; let i=index">
<input type="text" placeholder="Add Color Variation" formControlName="color">
</div>
</div>
</form>
</div>
</div>