首页 > 解决方案 > 无法访问插值 {{}} 设置的输入字段值

问题描述

我正在开发一个非常简单的应用程序,它包含一个带有 formArray 的表单。在 formArray 中可以选择产品名称和数量。当两者都被选中时,第三个输入字段 -总计- 计算材料的总价格(产品价格 * 金额),使用

<input matInput placeholder="total"
  type="number"
  formControlName="total"
  value="{{getProductPrice(purchaseForm.value.product[i].productId) * purchaseForm.value.product[i].amount}}">

我想对 formArray 中所有项目的总输入字段(价格)求和。该值呈现正常,如果我更改任何产品和/或金额,它会自动更改。

我的问题是,当我尝试访问输入字段的值时,我得到 0。如果我手动更改值(粘贴、键入等),我可以立即访问它。

我可以访问其他字段(fex。我可以计算所有产品的总和)

问题是因为我设置字段值的方式造成的吗?

有人知道为什么会这样吗?

标签: angularformsstring-interpolation

解决方案


//create an array of totals
totals:number[]=[];
total:number; //<--use a variable to store the total

//After create the form Array
this.yourFormArray.valueChanges(res=>{
   let total=0;
   res.forEach((x:any,index:number)=>{
     //use the "+" to convert to number res.amount;
     totals[index]=(+x.amount)*(this.getProductPrice(x.productId));
     total+=totals[index]
   })
   this.total=total;
}

推荐阅读