Reputation: 432
I have a looped table row which contains a form. I want to update the total field based on the price & quantity in reactive forms. Code is
<tbody formArrayName="products">
<tr *ngFor="let phone of productForms.controls; let i=index" [formGroupName]="i">
<th scope="row">{{i+1}}</th>
<td><input type="text" class="form-control" placeholder="Product Code" formControlName="product_code"></td>
<td><input type="text" class="form-control" placeholder="Product Name" formControlName="product_name"></td>
<td><input type="number" class="form-control" placeholder="Price" formControlName="product_price"></td>
<td><input type="number" class="form-control" placeholder="Quantity" formControlName="product_quantity"></td>
<td><input type="number" class="form-control" formControlName="total" disabled></td>
<td><button type="button" class="btn btn-danger ml-2" (click)="deleteProduct(i)">Remove</button></td>
</tr>
</tbody>
How to update the total value at the time of entering the Price & Quantity. The typescript code is:
ngOnInit() {
this.myForm = this.fb.group({
customer_name: '',
customer_phone: '',
customer_address: '',
products: this.fb.array([0])
});
}
get productForms() {
return this.myForm.get('products') as FormArray;
}
addProduct() {
const product = this.fb.group({
product_code: [],
product_name: [],
product_price: [],
product_quantity: [],
total: []
});
this.productForms.push(product);
}
Upvotes: 1
Views: 706
Reputation: 24472
You may consider using template variables like this
<td><input type="number" class="form-control" placeholder="Price" formControlName="product_price" #price></td>
<td><input type="number" class="form-control" placeholder="Quantity" formControlName="product_quantity" #quantity></td>
<td><input type="number" class="form-control" [value]="(price.value || 0) * (quantity.value || 0)" disabled></td>
get the total for all products
component
getProductsTotalPrice() : number {
let total = 0;
for(let product of productForms.controls){
total += (+product.get('price').value || 0) * (+product.get('quantity').value || 0)
}
return total;
}
template
<span>{{getProductsTotalPrice}}</span>
Upvotes: 1