You need to enable JavaScript to run this app. Angular Material mat-table 如何实现两列相乘的第三列计算并解决行小计联动异常
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material mat-table 如何实现两列相乘的第三列计算并解决行小计联动异常

问题说明

基于Angular Material开发带下拉选择列的服务报价表格,预期效果是用户选中某一行的服务时长后,按该行服务的月度单价独立计算对应小计,最终汇总所有已选服务的总费用。
当前存在的异常:所有行的小计计算值,会跟随用户最后一次在任意行选择的月份数同步变化——哪怕之前已经手动选定过月份的行没有做任何修改,小计也会被异常联动更新。

异常根因

现有代码的核心问题是把月份选择的结果统一存在了组件级别的全局变量serviceLength上:

  • 选择任意行的月份时,都会把选中值直接覆盖给这个全局变量,没有做行级别的隔离
  • 所有行的小计计算都直接引用这个全局变量的值,没有绑定对应行的独立数据
    这就导致全局变量被修改后,所有行的计算逻辑拿到的都是同一个最新值,自然会出现全部行跟着联动变化的问题。
修复实现

核心修改思路

把原本全局共享的月份值,拆分存储到每一行的数据对象上,让每行的选中状态、小计计算都完全独立,从根源上切断行间联动。同时补充总费用的实时计算逻辑,匹配预期的报价需求。

模板代码调整

替换原来的月份选择列、小计列代码,补充总费用展示模块:

<!-- 原价格列保持不变 -->
<ng-container matColumnDef="price">
  <mat-header-cell *matHeaderCellDef mat-sort-header> Price (USD/m) </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.price | currency}} </mat-cell>
</ng-container>

<!-- 修改后的月份选择列 -->
<ng-container matColumnDef="month">
  <mat-header-cell *matHeaderCellDef> Months </mat-header-cell>
  <mat-cell *matCellDef="let element">
    <mat-select 
      placeholder="0" 
      [(ngModel)]="element.selectedMonths"
      (selectionChange)="calculateTotal()"
    >
      <mat-option *ngFor="let month of months" [value]="month.value">
        {{ month.viewValue }}
      </mat-option>
    </mat-select>
  </mat-cell>
</ng-container>

<!-- 修改后的小计列 -->
<ng-container matColumnDef="subtotal">
  <mat-header-cell *matHeaderCellDef> SubTotal </mat-header-cell>
  <mat-cell *matCellDef="let element">
    {{ element.price * (element.selectedMonths || 0) | currency }}
  </mat-cell>
</ng-container>

<!-- 表格下方补充总费用展示 -->
<div class="total-area" style="text-align: right; padding: 16px 0; font-weight: 600;">
  合计总费用:{{ totalFee | currency }}
</div>

TypeScript逻辑调整

删掉全局共享的serviceLength变量,替换行绑定逻辑、补充总费用计算:

export class StockAddsubsComponent implements OnInit {
  columnsToDisplay: string[] = ['id','name','price','month','subtotal'];
  listData: MatTableDataSource<any>;
  months = [
    {value: 1, viewValue: 1}, 
    {value: 3, viewValue: 3}, 
    {value: 6, viewValue: 6}, 
    {value: 12, viewValue: 12}
  ];
  totalFee: number = 0;

  @ViewChild(MatSort) sort: MatSort;

  constructor(private feesService: FeesService) { }

  ngOnInit(): void {
    this.createFeeList();
  }

  createFeeList() {
    this.feesService.getFeeList().subscribe((data: any[]) => {
      // 给每条服务数据初始化默认选中月份,避免双向绑定报错
      const processedList = data.map(item => ({
        ...item,
        selectedMonths: 0
      }));
      this.listData = new MatTableDataSource(processedList);
      this.calculateTotal();
    }, error => {
      console.log(error);
    });
  }

  // 遍历所有行累加计算总费用
  calculateTotal() {
    if (!this.listData?.data?.length) return;
    this.totalFee = this.listData.data.reduce((sum, currentRow) => {
      return sum + currentRow.price * (currentRow.selectedMonths || 0);
    }, 0);
  }
}
修复效果
  • 每行的月份选择值独立存储在当前行的对象上,不会和其他行共享
  • 每行的小计计算只读取本行的单价、本行选中的月份数,不会被其他行的操作影响
  • 每次修改任意行的选择值,都会实时触发总费用计算,完成金额汇总

内容的提问来源于stack exchange,提问作者canbrian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.23 19:06:04