Angular点击Add按钮时汇总区累加展示商品名与价格(解决覆盖问题)
问题根因
商品名称、单价使用单个变量存储,每次点击Add按钮都会直接覆盖变量的上一次值,因此汇总区仅能展示最后一次添加的商品信息。总价累加逻辑正常运行,是因为总价计算使用了+=累加操作,没有发生值覆盖。
另外同一按钮绑定3个独立click事件属于冗余写法,可合并为单个方法统一处理逻辑。
修复步骤
1. 调整组件TS代码
将单值的名称、单价变量替换为数组,用于存储所有已选商品,同时合并分散的点击处理方法:
// 定义已选商品的数据结构 interface SelectedProduct { name: string; price: number; } export class BookingComponent implements OnInit { bookAdd: Booking[] = []; total = 0; // 替换原有的单值name、price变量,用数组存储所有已选商品 selectedProducts: SelectedProduct[] = []; constructor(private booking: BookingService) {} ngOnInit(): void { this.booking.getBooking().subscribe((data) => { this.bookAdd = data; }); } // 合并原有的三个点击方法,一次完成总价累加、商品信息存储 addProductToSummary(name: string, price: number) { this.total += price; this.selectedProducts.push({ name, price }); } }
2. 调整模板HTML代码
将按钮上的多个click绑定替换为统一的方法调用,同时在汇总区遍历已选商品数组,渲染所有已添加的条目:
<table class="container table table-striped table-hover"> <thead> <tr> <th scope="col">Activity</th> <th scope="col">Name</th> <th scope="col">1 hour</th> <th scope="col">30 min.</th> </tr> </thead> <tbody> <tr *ngFor="let item of bookAdd"> <td>img</td> <td>{{ item.name }}</td> <td *ngFor="let pointer of item.price"> {{ pointer }} <button type="button" class="btn btn-dark btn-sm" (click)="addProductToSummary(item.name, pointer)" > Add </button> </td> </tr> </tbody> </table> <div class="container"> <div class="row"> <div class="col-3 card"> <h3 class="center">summary</h3> <!-- 遍历已选商品数组,展示所有添加的条目 --> <p *ngFor="let product of selectedProducts"> {{ product.name }} - {{ product.price }} </p> <h4>total {{ total }}</h4> </div> </div> </div>
可选优化
如果后续需要支持删除已选商品、统计同商品购买数量,可直接基于selectedProducts数组操作,总价也可以改为通过数组reduce方法实时计算,避免单独维护total变量导致的数值和商品列表不同步问题。
内容的提问来源于stack exchange,提问作者Muhammad Qandil
相关产品推荐
相关产品推荐

