Angular - 2.28 Get the index when using ngFor

In the previous video we built a log mechanism that stored ascending numbers in an array. We then used that number to decide whether to apply a blue background and the white-text class. The exercise hinted at two ways to make the solution more realistic: replace the ascending number by a more meaningful content (such as a timestamp), or rely on the position of the element in the array rather than on its value. This lesson shows the second technique.

First, let's update the log to push a real timestamp instead of a counter: this.log.push(new Date());. Date is a built-in JavaScript object, no import required. After clicking the button a few times, all rows now show a date string - but they are all blue because the previous condition compared a Date object with the number 5, which is always considered greater. We need a different criterion.

Extract the iteration index from *ngFor

  • The *ngFor directive accepts additional bindings separated by semicolons.
  • To get the current index we write: *ngFor="let logItem of log; let i = index" (the variable name i is up to you).
  • We can now reference i inside the same template - for property bindings, structural bindings or interpolation.

We update the styling expressions accordingly: [ngStyle]="{ backgroundColor: i >= 4 ? 'blue' : 'transparent' }" [ngClass]="{ 'white-text': i >= 4 }". The index starts at zero, so position 4 corresponds to the fifth element - exactly what we wanted. With this change the styling works whatever data we choose to put inside the log: timestamps, strings, custom objects.

This little trick is one of the most useful additions to *ngFor. You can also extract first, last, odd and even with the same semicolon syntax. With these tools you now have a solid grasp of the Angular basics and we are ready to set up the official course project in the next section, before diving deeper into components and data binding.