是否可以将ngFor的每个值添加为一个值?

时间:2019-10-17 05:53:11

标签: arrays angular ngfor

“总计”列中ngFor返回了一些值。现在,我想添加这些值以获得一个grandTotal。我不知道。有人可以帮助我吗?

在第二个表格下面:

我希望添加{{sales.Total}}个值并返回总计。

/ *****第一张桌子***** /

              <table class="table">
                <thead>
                    <tr>
                        <th scope="col">S.N</th>
                        <th scope="col">Items</th>
                        <th scope="col">Quantity</th>
                        <th scope="col">Rate</th>
                        <th scope="col">Total</th>
                    </tr>
                </thead>
                <tbody>
                        <tr *ngFor="let sales of salesTransaction, let i = index">
                            <th>{{i+1}}</th>
                            <!-- <td mat-cell *matCellDef="let salesTransaction">{{salesTransaction.ProductName}}</td> -->
                            <td>{{sales.ProductName}}</td>
                            <td>{{sales.Quantity}}</td>
                            <td>{{sales.Rate}}</td>
                            <td>{{sales.Total}}</td>
                        </tr>

                </tbody>
            </table>

/ *****第二张表***** /

            <table class="right-table">
                <tbody>
                    <tr>
                        <th>Sub-Total</th>
                            <td *ngFor="let sales of salesTransaction">{{sales.Total}}</td>
                    </tr>
                    <hr class="divider">
                    <tr>
                        <th>Tax</th>
                            <td>Happy</td>
                    </tr>
                    <hr class="divider">
                    <tr>
                        <th>Grand Total</th>
                            <td>0000</td>
                    </tr>
                </tbody>
            </table>

2 个答案:

答案 0 :(得分:3)

您需要创建一个返回总计的方法

   getGrandTotal(): number {
        return this.salesTransaction.reduce((acc, val) => acc += val.Total, 0);
      }

<tr>
  <th>Grand Total</th>
   <td>{{getGrandTotal()}}</td>
</tr>

答案 1 :(得分:1)

<table class="right-table">
                <tbody>
                    <tr>
                        <th>Sub-Total</th>
                            <td *ngFor="let sales of salesTransaction">{{sales.Total}}</td>
                    </tr>
                    <hr class="divider">
                    <tr>
                        <th>Tax</th>
                            <td>Happy</td>
                    </tr>
                    <hr class="divider">
                    <tr>
                        <th>Grand Total</th>
                            <td>{{salesTransaction.reduce((total, value) => total += value.Total, 0)}}</td>
                    </tr>
                </tbody>
            </table>