Angular & Signals (283 Qs)•Part 8: Internationalization (i18n), Testing & DOM Directives (177 - 212)
What is index property in ngFor directive?
The index property returns the zero-based numeric position of each item during a template iteration. Angular provides contextual variables in both the Classic Built-in Directive (*ngFor) and the Modern Built-in Control Flow (@for).
1. Classic *ngFor Contextual Variables
In classic *ngFor, you declare template input variables using the let varName = property syntax:
html
<ul>
<li *ngFor="let todo of todos; let i = index; let isFirst = first; let isLast = last; let isEven = even; let isOdd = odd; let total = count">
[{{ i + 1 }} of {{ total }}] {{ todo.name }}
<span *ngIf="isFirst" class="badge">FIRST</span>
<span *ngIf="isLast" class="badge">LAST</span>
</li>
</ul>
2. Modern Built-in Control Flow: @for Variables (Angular 17+)
In modern @for, Angular provides built-in contextual variables prefixed with $ that are accessible directly inside the loop:
html
<ul>
@for (todo of todos; track todo.id; let i = $index, total = $count) {
<li [class.even-row]="$even" [class.odd-row]="$odd">
[{{ i + 1 }} of {{ total }}] {{ todo.name }}
@if ($first) { <span class="badge">FIRST</span> }
@if ($last) { <span class="badge">LAST</span> }
</li>
}
</ul>
3. Available Contextual Variables Reference Table
Variable Name (*ngFor) | Built-in Variable (@for) | Type | Description |
|---|---|---|---|
index | $index | number | Zero-based index of the current item (0, 1, ...). |
count | $count | number | Total number of items in the iterable. |
first | $first | boolean | true if current item is the first item. |
last | $last | boolean | true if current item is the last item. |
even | $even | boolean | true if current index is an even number. |
odd | $odd | boolean | true if current index is an odd number. |