我正在尝试计算每个订单项的总计,但它在更改数量时只计算一次数组中的第一个总计

I am trying to calculate the total for each line item, but it only calculates the first total in the array a single time when changing the quantity

component.ts

我不确定为什么我的 for 循环没有计算数组中每一项的总数?

ngOnInit(): void {
  this.billLineItemsQuantityOnChange(this.billLineItems);
}

get billLineItems(): FormArray {
  return this.billForm.get('billLineItems') as FormArray;
}

calculateBillLineItemsTotal(billLineItems: FormArray): void {
  for(let i = 0; i <= billLineItems.length; i++) {
    const amount = billLineItems.at(i).get(['amount']);
    const quantity = billLineItems.at(i).get(['quantity']);
    const total = billLineItems.at(i).get(['total']);
    const calcTotal = amount!.value * quantity!.value;
    total!.setValue(calcTotal)
  }
}

billLineItemsQuantityOnChange(billLineItems: FormArray): void {
  for(let i = 0; i <= billLineItems.length; i++) {
    const amount = billLineItems.at(i).get(['amount']);
    const quantity = billLineItems.at(i).get(['quantity']);
    quantity!.valueChanges.subscribe(() => {
      if (amount!.value !== null && quantity!.value !== null) {
        this.calculateBillLineItemsTotal(billLineItems);
      }
    });
  }
}

我将计算逻辑位置更改为保持循环抛出控件的 createBillLineItem 方法,并将子部分设置为 return 表单组

之前数量和金额的值更改
  createBillLineItem(): FormGroup {

    const fg  =this.fb.group({
      description: [null],
      amount: 0,
      quantity:0,
      total: 0,
    });

     fg.get('quantity').valueChanges.subscribe((qty) => {
       const amount  = +fg.get('amount').value || 0 ;
       fg.get('total').setValue(amount * +qty)
      });


     fg.get('quantity').valueChanges.subscribe((amount) => {
       const qty  = +fg.get('amount').value || 0 ;
       fg.get('total').setValue(amount * +qty)
      });

    return fg;
  }

demo