Reputation: 9043
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);
}
}
Upvotes: 0
Views: 919
Reputation: 21
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;
}
Upvotes: 1
Reputation: 662
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>
Upvotes: 2
Reputation: 18647
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>
Upvotes: 1