我每年都有一份结果清单。
<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>
如何从循环中的当前结果中减去previus结果?
这是我想要使用常规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);
}
}
答案 0 :(得分:2)
这只是一个想法。您可以初始化一个名为indexArray
的数组,如[0,1,2,3,4,5,6],并将其用于循环,如下所示
<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>
答案 1 :(得分:1)
您可以随时获取index
,
所以,你可以使用
{{histroricalData[i - 1].OverallResult - histroricalData[i].OverallResult}}%
,或者
{{(histroricalData[i - 1]['OverallResult']) - (histroricalData[i]['OverallResult'])}}%
代码变为,
<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>
答案 2 :(得分:1)
它适合你。 模板:
<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文件:
getCalculatedValue(value){
return Math.round(value * 100) / 100;
}