我有一个包含表格的循环表行。我想以反应式形式基于价格和数量更新总字段。代码是
lm(r ~ 0 + X)
如何在输入价格和数量时更新总价值。 打字稿代码为:
<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>
答案 0 :(得分:1)
您可以考虑使用这样的模板变量
<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>