如何在ng2-smart-table(Angular2)中实现Qty*Price计算并生成Amount列
刚好之前做过类似的需求,给你一步步拆解怎么在ng2-smart-table里实现Qty*Price计算Amount,同时获取Amount和Subtotal的值:
1. 配置表格列,实现实时计算Amount
首先在你的表格配置里,我们要给Qty和Price列添加编辑监听,当用户修改这两个值时自动计算Amount;同时给Amount列设置不可编辑,并确保显示时能正确渲染计算结果。
这里是核心的列配置代码:
import { Ng2SmartTableComponent } from 'ng2-smart-table'; import { ViewChild } from '@angular/core'; // 组件内的表格配置 settings = { columns: { qty: { title: 'Qty', type: 'number', editor: { type: 'number', // 监听Qty输入变化 onComponentInitFunction: (component) => { component.valueChanges.subscribe(() => { this.updateRowAmount(component.row); }); } } }, price: { title: 'Price', type: 'number', editor: { type: 'number', // 监听Price输入变化 onComponentInitFunction: (component) => { component.valueChanges.subscribe(() => { this.updateRowAmount(component.row); }); } } }, amount: { title: 'Amount', type: 'number', editable: false, // 禁止手动编辑,由计算生成 // 确保初始化或刷新时能正确显示计算值 valuePrepareFunction: (_, row) => (row.qty || 0) * (row.price || 0) } } }; // 表格实例,用于后续刷新和获取数据 @ViewChild(Ng2SmartTableComponent) table!: Ng2SmartTableComponent;
然后添加计算单条行Amount的方法:
updateRowAmount(row: any) { // 处理空值,避免NaN const qty = row.qty || 0; const price = row.price || 0; row.amount = qty * price; // 刷新表格让Amount列显示最新值 this.table.refresh(); }
2. 初始化数据时计算Amount
如果你的表格有初始数据,记得在组件初始化时先给每条数据计算好Amount:
data: any[] = [ // 你的初始数据,比如 { qty: 2, price: 10 } ]; ngOnInit() { // 给初始数据批量计算Amount this.data.forEach(row => { row.amount = (row.qty || 0) * (row.price || 0); }); // 初始化计算Subtotal this.calculateSubtotal(); }
3. 获取Amount和计算Subtotal
要获取单条行的Amount很简单,直接从表格的行数据里取row.amount即可。如果需要计算所有行的Subtotal(也就是所有Amount的总和),可以监听表格数据的变化,实时更新总和:
subtotal = 0; ngAfterViewInit() { // 监听表格数据的增删改操作,实时计算Subtotal this.table.source.onChanged().subscribe((change) => { const triggerActions = ['edit', 'add', 'delete']; if (triggerActions.includes(change.action)) { this.calculateSubtotal(); } }); } calculateSubtotal() { // 获取所有行数据,累加Amount const tableData = this.table.source.data; this.subtotal = tableData.reduce((total, row) => total + (row.amount || 0), 0); }
这样不管是编辑现有行、新增行还是删除行,Subtotal都会自动更新啦。
额外提示
- 记得处理空值:用
|| 0确保qty或price为空时不会出现NaN - 如果需要格式化Amount或Subtotal(比如保留两位小数),可以在
valuePrepareFunction或者计算时用toFixed(2)处理 - 如果是新增行,当用户输入Qty或Price时,同样会触发计算,不需要额外处理
内容的提问来源于stack exchange,提问作者Aswani




