Angular响应式表单FormArray如何计算单项总价与合计总金额
实现方案
1. 先调整TS文件逻辑(medicinepurchase.component.ts)
首先导入必要依赖,新增订阅管理、单行总价计算、总金额自动计算逻辑:
// 顶部新增导入 import { Subscription } from 'rxjs'; import { OnDestroy } from '@angular/core'; // 类定义修改为同时实现OnInit和OnDestroy export class MedicinePurchaseComponent implements OnInit, OnDestroy { // 新增订阅管理属性,避免内存泄漏 private subs: Subscription[] = []; // 原有属性保持不变 ... private initForm() { this.medicinePurchaseForm = new FormGroup({ prescriptionId: new FormControl(), subtotal: new FormControl(0), // 初始化默认值为0 purchaseMedicineList: new FormArray([]) }); // 监听药品列表所有值变化,自动计算总金额 const arraySub = this.medicineArray.valueChanges.subscribe(list => { const subTotal = list.reduce((sum, item) => sum + Number(item.itemTotal || 0), 0); this.medicinePurchaseForm.get('subtotal').setValue(subTotal, { emitEvent: false }); }); this.subs.push(arraySub); } getLineFormGroup(){ const lineItem = this.fb.group({ medicineId: new FormControl(this.medicineID.value, Validators.required), medicineName: new FormControl(this.brandName.value, Validators.required), unitPrice: new FormControl(this.price.value), quantity: new FormControl(this.quantity.value, Validators.required), itemTotal: new FormControl(0), // 初始化默认值为0 }); // 监听当前行单价、数量变化,自动计算单行总价 const lineSub = lineItem.valueChanges.subscribe(val => { const total = Number(val.unitPrice || 0) * Number(val.quantity || 0); lineItem.get('itemTotal').setValue(total, { emitEvent: false }); }); this.subs.push(lineSub); // 新增行时先初始化计算一次单行总价 const initTotal = Number(lineItem.get('unitPrice').value || 0) * Number(lineItem.get('quantity').value || 0); lineItem.get('itemTotal').setValue(initTotal, { emitEvent: false }); return lineItem; } // 新增销毁生命周期,取消所有订阅 ngOnDestroy(): void { this.subs.forEach(s => s.unsubscribe()); } // 其他原有方法保持不变 ... }
2. 调整HTML模板(medicinepuechase.component.html)
优化显示逻辑,新增总金额展示位:
<!-- 表格行内价格展示简化,直接取itemTotal的值 --> <tr *ngFor="let medicine of medicineArray.controls; index as t" [formGroupName]="t"> <td><input type="text" formControlName="medicineId" placeholder="ID" /></td> <td><input type="text" formControlName="medicineName" placeholder="Name" /></td> <!-- 数量输入改为number类型避免非法输入 --> <td><input type="number" min="1" placeholder="quantity" formControlName="quantity" ></td> <td><input type="text" placeholder="Item Total" formControlName="itemTotal" readonly></td> <td>Price: {{medicine.get('itemTotal').value | number:'1.2-2'}}</td> </tr> </table> <!-- 新增总金额展示 --> <div style="margin-top: 15px; text-align: right; font-weight: bold;"> 合计总金额:{{medicinePurchaseForm.get('subtotal').value | number:'1.2-2'}} 元 </div>
调整后新增药品、修改单条药品的数量/单价时,单行总价和总合计都会自动同步更新。
内容的提问来源于stack exchange,提问作者MD SHAFFAT
相关产品推荐
相关产品推荐

