html - 在 Angular 中,当我更新对象的某个字段时,对象数组无法保留值
对象数组是一种表单数组,即 products:formBuilder.array([]) 我正在尝试更新一个对象。有多个产品,用户可以选择更新数量。例如:
product1.quantity :2
product2.quantity :5
当用户点击第一个产品的更新产品数量按钮时,数量变为3,但当用户尝试更新产品2时,产品2的数量更新为6,但产品1的数量变回2。
更新数量 产品1:
product1.quantity:3
product2.quantity:5
更新产品2的数量:
product1.quantity:2
product2.quantity:6
我无法理解这种行为。以下是供您参考的代码片段:.ts 文件代码(在按钮点击时调用的函数)
console.log(JSON.parse(JSON.stringify(this.productsinvoice.value)));
this.productsinvoice.value.forEach(productInvoice => {
if(productInvoice.productID === this.productID){
productInvoice.quantity = this.product_quantity;
}
});
console.log(JSON.parse(JSON.stringify(this.productsinvoice.value)));
HTML 代码
<div *ngFor="let product_details_tax of newrequest?.get('productsinvoice')['controls']; let i=index"
[formGroupName]="i">
<div class="row">
<div class="form-group col formgroup_mar_bottom">
<label for="inputRate4">Product Name</label>
<input type="text" class="form-control" id="inputRate4"
formControlName='productname' placeholder="Enter Product Name">
</div>
<div class="form-group col formgroup_mar_bottom">
<label for="inputAmount">Quantity</label>
<input type="number" class="form-control" id="inputAmount4"
formControlName='quantity'
value={{product_details_tax.value?.quantity}}
placeholder="Enter Quantity">
</div>
编辑:
this.productsinvoice.value = this.productsinvoice.value.map(productInvoice => {
if(productInvoice.productID === this.productID){
console.log(this.product_quantity);// prints the new quantity
return {
...productInvoice,
quantity: this.product_quantity
}
console.log(productInvoice)// logs new value of quantity
}else{
return productInvoice
}
});
console.log(this.productsinvoice.value);//logs the object with old quantity.
当我使用扩展运算符时,数量甚至第一次都不会更新。
答案#1
你可以创建一个临时数组,在该数组中更新值,然后调用 setValue 函数
let tempArr = productsInvoice
loop through tempArr to update your value
productsInvoice.setValue(tempArr)
答案#2
使用双向绑定,所以将 value={{product_details_tax.value?.quantity}} 改为 [(value)]="product_details_tax.value?.quantity"
这样你就不需要手动更改数值,当用户更改输入数值时,模型应随之改变。
查看说明:https://www.javatpoint.com/two-way-data-binding-in-angular-8
