I am using Angular 4 with reactive forms. I have an array of form that I am trying to associate with an array that I am tracking in my component. I use reactive forms, so I can get confirmation, so I do not want to use the template form approach.
I add elements to the form array as follows:
createFormWithModel() { this.orderForm = this.fb.group({ orderNumber: [this.order.ProductBookingOrder], orderDate: [this.order.PurchaseOrderIssuedDate], lineDetailsArray: this.fb.array([]) }) const arrayControl = <FormArray>this.orderForm.controls['lineDetailsArray']; this.order.ProductBookingDetails.forEach(item => { let newGroup = this.fb.group({ ProductName: [item.ProductName], Quantity: [item.ProductQuantity.Quantity], UOM: [item.ProductQuantity.UOM], RequestedShipDate: [item.RequestedShipDate] }) }) }
The order form is obviously my reactive FormGroup forms. an order is my object that I receive from my API, and I want to update its values, including row data. I think I should use "valueChanges.subscribe" for each new group, but I'm not sure how to get the index of the item that has been changed. Any thoughts?
newGroup.valueChanges.subscribe('i want value and index some how' => { this.order.ProductbookingDetails[index].ProductName = value.ProductName; });
Here is the HTML for this part:
<tbody formArrayName="lineDetailsArray"> <tr [formGroupName]="i" *ngFor="let line of orderForm.controls['lineDetailsArray'].controls; index as i"> <td><input class="form-control" type="text" placeholder="Product Name" formControlName="ProductName" required/></td> <td><input class="form-control" type="number" step=".01" (focus)="$event.target.select()" placeholder="Quantity" formControlName="Quantity"/></td> <td><input class="form-control" readonly formControlName="UOM"></td> <td><date-picker formControlName="RequestedShipDate" format="L" [showClearButton]="false"></date-picker></td> <td><button type="button" (click)="deleteLineDetail(i)">Remove</button></td> </tr> </tbody>
Kevin source share