我有一个包含表格的循环表行。我想根据反应式形式的价格和数量更新总字段。代码是
<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>
输入价格和数量时如何更新总值。打字稿代码为:
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);
}
您可以考虑使用这样的模板变量
<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>
得到所有产品的总数
零件
getProductsTotalPrice() : number {
let total = 0;
for(let product of productForms.controls){
total += (+product.get('price').value || 0) * (+product.get('quantity').value || 0)
}
return total;
}
模板
<span>{{getProductsTotalPrice}}</span>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句