简体   繁体   中英

Calculating within ngFor Angular 2

I have a list of results from year to year.

<tr *ngFor="let d of histroricalData; let i = index">
  <td>
    {{d.YearCalculation}}
  </td>
  <td>
    {{d.OverallResult}}%
  </td>
  <td>
    <!--subtract previous year from current -->
  </td>
</tr>

How would I subtract the previus result from the current one in the loop?

This is what I want to achieve using a regular for loop

 for (let i = 0; i < this.histroricalData.length; i++) {
      if (this.histroricalData[i - 1] != null) {
        let calc = this.histroricalData[i].OverallResult - this.histroricalData[i - 1].OverallResult
        console.log(Math.round(calc * 100) / 100);
      }
    }

This a just a idea. You can initialize a array called indexArray something like [0,1,2,3,4,5,6] and use it for the loop as follows

<tr *ngFor="let d of histroricalData; let i of indexArray">
      <td>
        {{d.YearCalculation}}
      </td>
      <td>
        {{d.OverallResult}}%
      </td>
      <td *ngIf="histroricalData[i - 1] != null">
        {{histroricalData[i].OverallResult - histroricalData[i - 1].OverallResult}}
      </td>
</tr>

You can always take help of index ,

So, you can use

 {{histroricalData[i - 1].OverallResult - histroricalData[i].OverallResult}}%

or,

 {{(histroricalData[i - 1]['OverallResult']) - (histroricalData[i]['OverallResult'])}}%

The code becomes,

<tr *ngFor="let d of histroricalData; let i = index">
  <td>
    {{d.YearCalculation}}
  </td>
  <td>
    {{histroricalData[i - 1].OverallResult - histroricalData[i].OverallResult}}%
  </td>
  <td>
    <!--subtract previous year from current -->
  </td>
</tr>

It works for you. template:

<tr *ngFor="let d of histroricalData; let i = index">
  <td>
    {{d.YearCalculation}}
  </td>
  <td>
    {{d.OverallResult}}%
  </td>
  <td *ngIf="i > 0">
    {{getCalculatedValue(histroricalData[i].overallResult - histroricalData[i-1].overallResult)}}
  </td>
</tr>

ts file:

getCalculatedValue(value){
    return Math.round(value * 100) / 100;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM