首页 > 解决方案 > 角度表 - 列不是计算列的总计/汇总。只有在输入文本框中输入值时,总计才能正常工作

问题描述

html代码

<table>
     <thead>
        <tr>
          <th>Items</th>
          <th>Value</th>
          <th>% of value</th>
          <th>Rate</th>
          <th>Calculated Value</th>
        </tr>
     </thead>
      <tbody formArrayName="Details">
        <tr *ngFor="let item of Details.controls;">
          <td>
            <input class="width-15" matInput type="text" formControlName="ItemName" autocomplete="off">
          </td>
          <td>
            <input matInput type="text" mask="comma_separator.2" prefix="$" autocomplete="off" formControlName="Value">
          </td>
          <td>
            {{percentOfValue(item, Details.controls)}}
          </td>
          <td>
            <input matInput type="text" mask="comma_separator.2" suffix="%" autocomplete="off" formControlName="Rate">
          </td>
          <td>
            <input matInput type="text" mask="comma_separator" prefix="$" autocomplete="off"
                   formControlName="CalculatedValue" value="{{calculatedvalue(item)}}">
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>Totals</td>
          <td>
            ${{ sumColumnTotal('Value') }}
          </td>
          <td>
            {{ sumPercentColumnTotal('percentOfValue') }}  ------------- How to calculate the sum of this column???
          </td>
          <td>
            // No need of totals for rates.
          </td>
          <td>
            ${{ sumColumnTotal('Value') }}
          </td>
        </tr>
      </tfoot>
</table>

**.ts code**

CalculatedValue(item): string {
    return ((item.value.Value) * (item.value.Rate));
 }

//(项目值/所有行的总和)*100 - 动态列。当第二列的值发生变化时,第三列的值将自动更新。percentOfValue(item, allItems): string {

    const totalValue = allItems.map(c => c.value.Value)
      .reduce((sum, current) => {
        const value = current != null ? current : 0;
        return +this.tryCleanNumber(sum) + +this.tryCleanNumber(value);
      }, 0);
    if (totalValue === 0) {
      return '0%';
    }
    const percent = +this.tryCleanNumber(item.value.Value) / totalValue;

    // * 100 for percent, *100 again and /100 for rounding
    const rounded = (percent * 100 );
    return rounded + '%';
  }

UI 中的结果表

在此处输入图像描述

红色高亮字段的问题:

  1. 当我们在文本框中(最后一列)输入值时,计算值列总计按预期工作。但是在值(第二列)中输入一些值,将自动填充/计算最后一列值(计算值)。换句话说,总计不适用于“计算列”,但在输入列时效果很好。
  2. 建议如何计算第三列的总和(价值的百分比)。由于列本身是计算列,因此无法在 ts 中编写任何函数。

标签: angularcalculated-columns

解决方案


推荐阅读