Angular中如何在*ngFor循环内获取当前输入框的ngModel绑定值
你现在的问题根源是所有循环生成的输入框,都双向绑定了组件全局的同一个discount变量,任意输入框修改都会更新这个全局变量,自然所有绑定它的输入框都会同步修改。
下面给出两种无需修改原有商品类定义的解决方案:
方案1:用映射对象存储各商品的折扣值(推荐,不会丢失历史输入)
第一步:组件类新增映射对象
在你的组件类里新增一个空对象,用来按商品唯一标识存储对应的折扣值,不需要改动原商品类的代码:
// 组件类中添加 discountRecord: Record<string | number, number> = {};
第二步:修改HTML绑定逻辑
把ngModel的绑定值换成映射对象中对应商品的属性,用商品的唯一字段(比如id,没有的话可以用prod.name + prod.price这类能唯一区分商品的组合)作为key:
<tr *ngFor="let prod of products"> <td>{{prod.name}}</td> <td>{{prod.price}}Dhs</td> <td> <input type="number" (keyup.enter)="calculateDiscount(prod)" [(ngModel)]="discountRecord[prod.id]" placeholder="0" > </td> </tr>
第三步:修改折扣计算逻辑
calculateDiscount(prod: {price: number, id?: string|number, name?: string}): void { // 拿到当前商品对应的折扣 const currentDiscount = this.discountRecord[prod.id] || 0; const currentDiscountTotal = (prod.price * currentDiscount) / 100; console.log(`当前商品折扣额:${currentDiscountTotal}`); // 计算全单折后总价的逻辑 let allDiscount = 0; Object.values(this.discountRecord).forEach(dis => { allDiscount += (dis || 0); }); this.totalwithDiscount = this.total - allDiscount; }
方案2:仅获取当前输入框的值,不存储历史输入
如果你不需要留存其他商品的折扣值,只需要取当前正在输入的输入框的值,可以直接传递输入框元素的取值,不需要双向绑定全局变量:
<input type="number" #currentDiscountInput (keyup.enter)="calculateDiscount(prod.price, currentDiscountInput.value)" placeholder="0" >
对应计算逻辑:
calculateDiscount(price: number, inputValue: string): void { const discount = Number(inputValue); if (isNaN(discount) || price === undefined) return; const discountTotal = (price * discount) / 100; console.log(discountTotal); this.totalwithDiscount = this.total - discountTotal; }
注意这个方案每次计算只会用当前输入的折扣,之前输入的其他商品折扣会丢失,只适合仅需要单次计算当前商品折扣的场景。
内容的提问来源于stack exchange,提问作者amilana
相关产品推荐
相关产品推荐

