InterviewHubPRO
Section Overview
Q203

Question 203 of 283

Part 8: Internationalization (i18n), Testing & DOM Directives (177 - 212)

72%
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)TypeDescription
index$indexnumberZero-based index of the current item (0, 1, ...).
count$countnumberTotal number of items in the iterable.
first$firstbooleantrue if current item is the first item.
last$lastbooleantrue if current item is the last item.
even$evenbooleantrue if current index is an even number.
odd$oddbooleantrue if current index is an odd number.