简体   繁体   English

在ngFor Angular 2中计算

[英]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循环实现的目标

 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 您可以像[0,1,2,3,4,5,6]一样初始化一个名为indexArray的数组,并将其用于循环,如下所示

<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 , 您随时可以借助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: ts文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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