Sub topic 7
Using $index, $first, $last, and the other implicit variables
This chapter assumes you can write an Angular component with a template, bind properties and events, and use signals. You should also know the basic @for syntax and why it requires a track expression. Here you will learn the six implicit variables that @for provides, how to alias them, and the mistakes people make with them.
What the implicit variables are
Inside an @for block, Angular makes six variables available without any declaration. They describe where the current item sits in the collection.
| Variable | Type | Meaning |
|---|---|---|
| `$index` | number | Zero-based index of the current row |
| `$count` | number | Total number of items in the collection |
| `$first` | boolean | `true` when the current row is the first one |
| `$last` | boolean | `true` when the current row is the last one |
| `$even` | boolean | `true` when `$index` is even |
| `$odd` | boolean | `true` when `$index` is odd |
You can use these names directly in the block body. This works for any binding or interpolation.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-steps',
template: `
<ol>
@for (step of steps(); track step) {
<li>
Step {{ $index + 1 }} of {{ $count }}: {{ step }}
@if ($first) { (start) }
@if ($last) { (finish) }
</li>
}
</ol>
`,
})
export class StepsComponent {
steps = signal(['Install', 'Configure', 'Deploy']);
}The output reads "Step 1 of 3: Install (start)", then "Step 2 of 3: Configure", then "Step 3 of 3: Deploy (finish)".
Index is zero-based
$index starts at 0. Add 1 when you show a number to a reader, as in {{ $index + 1 }}. This is the most common off-by-one mistake in list templates.
Relationships between the variables
The variables are derived from each other, so you never need to compute them yourself.
$evenis the same as$index % 2 === 0.$oddis the opposite of$even.$firstis the same as$index === 0.$lastis the same as$index === $count - 1.
With a single item, $first and $last are both true. With an empty collection the loop body never runs, so none of the variables exist. Use @empty for that case.
Aliasing with let
The implicit names are fixed. You can bind them to other names with a let clause after the track expression. Separate the aliases with commas.
import { Component, signal } from '@angular/core';
interface Task {
id: number;
title: string;
}
@Component({
selector: 'app-task-list',
template: `
<ul>
@for (task of tasks(); track task.id; let i = $index, isEven = $even) {
<li [class.striped]="isEven">{{ i + 1 }}. {{ task.title }}</li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
`,
})
export class TaskListComponent {
tasks = signal<Task[]>([
{ id: 1, title: 'Write spec' },
{ id: 2, title: 'Review pull request' },
]);
}The statement let i = $index, isEven = $even creates two local names. The syntax is let alias = $variable, and one let covers all the aliases you want.
Aliasing is optional while the original names still work. It becomes necessary when loops are nested, because an inner $index hides an outer one.
Nested loops
Each @for gets its own set of implicit variables. Inside the inner loop, $index refers to the inner loop. To reach the outer index, alias it in the outer loop.
import { Component, signal } from '@angular/core';
interface Row {
id: number;
cells: string[];
}
@Component({
selector: 'app-grid',
template: `
<table>
@for (row of rows(); track row.id; let rowIndex = $index) {
<tr>
@for (cell of row.cells; track $index) {
<td>R{{ rowIndex }}C{{ $index }}: {{ cell }}</td>
}
</tr>
}
</table>
`,
})
export class GridComponent {
rows = signal<Row[]>([
{ id: 10, cells: ['a', 'b'] },
{ id: 20, cells: ['c', 'd'] },
]);
}Here rowIndex is the outer index and $index is the inner one. Without the alias, the outer index would be unreachable from inside the inner block.
Common patterns
Separators between items
$last lets you put a separator between items without leaving a trailing one.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-tags',
template: `
<p>
@for (tag of tags(); track tag) {
<span>{{ tag }}</span>@if (!$last) {<span>, </span>}
}
</p>
`,
})
export class TagsComponent {
tags = signal(['angular', 'signals', 'templates']);
}The result is "angular, signals, templates" with no comma after the last tag.
Zebra striping
$odd and $even suit class bindings. CSS can do the same with :nth-child, so prefer CSS when it is enough. Use the variables when the stripe logic depends on component state.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-striped',
styles: `
.odd { background: #f4f4f4; }
`,
template: `
@for (name of names(); track name) {
<div [class.odd]="$odd">{{ name }}</div>
}
`,
})
export class StripedComponent {
names = signal(['Ada', 'Grace', 'Linus', 'Margaret']);
}Special treatment for the first item
Use $first to highlight or label the first row, for example a "Featured" badge on the first article.
@for (article of articles(); track article.id) {
<article [class.featured]="$first">
<h3>{{ article.title }}</h3>
</article>
}Variables and tracking
The implicit variables change when the collection changes. If you insert an item at the start of the list, every existing item moves down by one position. For tracked items that Angular reuses, $index, $first, $last, $even, $odd, and $count are updated in place. The DOM nodes stay, and only the bindings that depend on those variables are refreshed.
This matters for the choice of track expression.
- Tracking by a stable identifier such as
task.idkeeps each DOM node attached to its item. When an item moves, Angular moves the node and updates$index. - Tracking by
$indexties each DOM node to a position. When an item moves, the node stays in place and receives different data.
Tracking by $index is acceptable for a static list of primitive values, such as the cells arrays in the grid example. Prefer an identifier in every other case.
Using the variables in expressions
The implicit variables are ordinary template expressions, so they combine with the rest of the template syntax.
- In an event handler:
(click)="remove($index)"passes the position to a method. - In a class binding:
[class.last-row]="$last". - In a ternary:
{{ $first ? 'Top' : 'Item ' + $index }}. - In a nested
@if:@if ($index < 3) { ... }shows only the first three rows.
The last case works but has a cost. The loop still creates all items and then hides most of them. If you only need the first three, slice the data in the component, for example with a computed signal, and iterate over the result.
Passing the index to a handler
Deleting by index is easy to write, and it is also easy to get wrong when the list is filtered.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-removable',
template: `
<ul>
@for (item of items(); track item) {
<li>
{{ item }}
<button (click)="removeAt($index)">Remove</button>
</li>
}
</ul>
`,
})
export class RemovableComponent {
items = signal(['one', 'two', 'three']);
removeAt(index: number) {
this.items.update(list => list.filter((_, i) => i !== index));
}
}This is safe because $index refers to the same array the component holds. If the template iterated over a filtered or sorted copy, $index would be the position in that copy, not in items(). In that case pass the item or its id and look it up in the component.
Common mistakes
- Declaring the variables yourself. Writing
let index = $indexis fine, but writinglet $index = ...or using the oldlet i = indexform from*ngForis not. The block syntax uses the$-prefixed names as the source. - Using
indexinstead of$index. Plainindexrefers to a component property namedindex, or fails to compile if none exists. In@for, the$is part of the name. - Reading the variables outside the loop. They exist only inside the
@forbody. The@emptyblock cannot see them, because no item exists there. - Expecting a different order from
$evenand$odd. They follow$index, which starts at 0. The first row is even. - Forgetting that nested loops hide names. Alias the outer variables before you write the inner loop.
- Using
$indexfor tracking and for identity.track $indexis a performance choice. It does not make the position a stable identity for the item.
Comparing with *ngFor
The same information was available in *ngFor, but it was exported with a different syntax.
<!-- Before -->
<li *ngFor="let task of tasks; let i = index; let last = last; trackBy: trackById">
{{ i }} {{ task.title }}
</li>
<!-- After -->
@for (task of tasks; track task.id; let i = $index, last = $last) {
<li>{{ i }} {{ task.title }}</li>
}The differences are small but worth remembering.
- The
$prefix marks the built-in variables. - Aliases are separated by commas inside one
let, not by repeatedletclauses with semicolons. trackreplacestrackByand is required.- The variables are available under their
$names even if you never alias them. With*ngForyou had to export each one explicitly.
Summary of the decisions
| Need | Use |
|---|---|
| Display a human-readable row number | `$index + 1` |
| Show "n of total" | `$index + 1` and `$count` |
| Separator between items | `@if (!$last)` |
| Header or badge on the first row | `$first` |
| Alternating row style | `$odd` or `$even`, or CSS `:nth-child` |
| Reach an outer loop's index | Alias it with `let` before the inner loop |
| Remove a row | Pass `$index` only if the list is the source array, otherwise pass the item or id |
Exercise
A template shows a numbered list with @for (name of names(); track name; let i = $index). Names are sorted in the component, and a "Remove" button calls removeAt(i). The component sorts a copy with [...names()].sort() and the template iterates the sorted copy, but removeAt splices the original names() array by index. Users report that the wrong name is removed. What is the cause and what is the fix?
Show answer
$index is the position in the sorted copy, but removeAt applies it to the unsorted original, so the two positions differ. The fix is to pass the item itself, as in removeAt(name), and filter the original array by value (or by id). Alternatively, store the sorted list in the signal so the template and the method use the same array.
Exercise
Write an @for over items() that prints "1. a", "2. b", and so on, and adds the text "(last)" only after the final row. Then state what $first and $last are when the list has exactly one item.
Show answer
Use @for (item of items(); track item; let n = $index) { <p>{{ n + 1 }}. {{ item }} @if ($last) { (last) }</p> }. With exactly one item, both $first and $last are true, and $count is 1.
Exercise
In a table built from nested @for blocks, you need the text "Row 2, Column 1" for the third row and second cell. Which aliases do you need, and what do you write?
Show answer
Alias the outer index in the outer loop, for example @for (row of rows(); track row.id; let r = $index), then use the inner $index for the column. The expression is Row {{ r }}, Column {{ $index }}, which yields "Row 2, Column 1" for indexes 2 and 1. Add 1 to each if you want one-based numbers.