angular 2 how to totals column ngFor?

时间:2018-07-25 04:20:52

标签: angular

At the moment, I have several entries in the table. How can output one sum record of the total of all fields.

<table>
  <thead>
    <tr>
      <th>Total</th>
      <th>Done</th>
      <th>Not Done</th>
    </tr>
  </thead>
  <tbody>
   <tr *ngFor="let monitoring of monitorings">
     <td>{{monitoring.total}}</td>
     <td>{{monitoring.percent_done}}</td>
     <td>{{monitoring.percent_no_done}}</td>
   </tr>
  </tbody>
</table>

that is, I have here such records:

1) 1. Total = 3 Done = 100.0 % Not Done = 0.0 %
2. Total = 8 Done = 75.0 % Not Done = 25.0 %
3. Total = 2 Done = 100.0 % Not Done = 0.0 %
4. Total = 2 Done = 100.0 % Not Done = 0.0 %
5. Total = 1 Done = 0.0 % Not Done = 100.0 %

And should output one record like this:

2) Total = 16 Done = 81.25 % Not Done = 18.75 %

1 个答案:

答案 0 :(得分:1)

Create a function in you component to get the sum and call it on ui something like

in you component

getTotal(arr){
  return arr.reduce( (sum, curr) => sum + curr.Total,0 );
}

Then on ui

   <tr *ngFor="let monitoring of monitorings">
     ....
   </tr>


 <tr><td>{{getTotal(monitorings)}}</td></tr> 

This example is only for Total property same can be done for Done,Not Done etc