Angular *ngFor变量更新问题:点击后所有项值同步变更
问题根源分析
你遇到的问题核心在于所有列表项都绑定了同一个全局的quantity和subtotal变量,不管点击哪个商品的按钮,都会更新这个全局变量,所以所有项的显示自然会同步变成相同值——因为它们都指向同一个数据源。
解决方案:绑定每个商品自身的属性
其实不需要额外创建局部变量,只需要让每个购物车项(card对象)自己维护quantity和计算subtotal即可,这样每个项的状态都是独立的。
修改后的HTML代码
<CardView class="cardStyle" *ngFor="let card of shoppingCart; let i = index;"> <Label text="{{card?.product.productName}}" textWrap="false" class="product-title " row="1" col="0"></Label> <!-- 直接绑定当前card的quantity属性 --> <Label text="Quantity:{{card.quantity}}" textWrap="true" col="1" row="2" class="product-quantia"></Label> <!-- 直接在模板中计算subtotal,或者提前在card对象中维护 --> <Label text="subtotal:{{card.quantity * card.unitPrice}}" textWrap="true" col="1" row="2" class="product-quantia"></Label> <Button text="" class="item-share-shop-save" (tap)="increase(card, i)"></Button> </CardView>
修改后的TS组件代码
// 移除全局的quantity和subtotalResult变量,不需要了 increase(card: any, id: number){ // 直接更新当前card的quantity属性,加个默认值避免初始为undefined的情况 card.quantity = (card.quantity || 0) + 1; // 可选:如果想提前计算subtotal存到card对象里,也可以加这行 // card.subtotal = card.quantity * card.unitPrice; }
补充说明
- 建议初始化
shoppingCart数组时,给每个card对象设置默认的quantity值(比如1),避免模板中出现undefined的显示问题。 - 如果觉得模板中直接计算
card.quantity * card.unitPrice不够优雅,也可以在increase方法里同步更新card.subtotal,然后模板中直接绑定card.subtotal即可。
这样修改后,每个购物车项的数量和小计都会独立更新,不会再出现所有项同步变化的问题啦!
内容的提问来源于stack exchange,提问作者Kevin Dias
相关产品推荐
相关产品推荐

