All topics
Directivesintermediate

New Control Flow with the @for Block

Explain the @for block, its mandatory track expression, and how it improves on *ngFor's trackBy.

@for replaces *ngFor as the built-in way to render a list in a template, and the single biggest difference an interviewer expects you to know is that track is mandatory, not optional. With *ngFor, providing a trackBy function was a performance optimization most developers skipped, silently paying the cost of full DOM node recreation on every list change; @for refuses to let you skip it, forcing you to make an explicit, informed choice.

It's like a coat check that tags each coat with the owner's ticket stub instead of guessing by position on the rack — when people leave and new people arrive, the attendant moves only the coats that actually changed hands, instead of re-hanging every coat in the room.

Key Concepts

1
The track expression tells Angular how to identify "the same item" across re-renders — typically a unique id (track item.id) — so that when the underlying array changes, Angular can diff by identity and only touch the DOM nodes that actually correspond to added, removed, or reordered items, instead of tearing down and rebuilding everything.
tracktrack item.id
2
@for also introduces a richer, built-in set of contextual variables than *ngFor did: $index, $first, $last, $even, $odd, and $count, all available without extra let- template variable declarations, plus a mandatory @empty block that renders when the collection has zero items — replacing a manual *ngIf="items.length === 0" sibling check that was easy to forget.
@for*ngFor$index$first$last
3
Interviewers sometimes test whether you understand that @for's new diffing algorithm (built specifically for this block, distinct from the old NgForOf/IterableDiffer machinery) was measured to be significantly faster in Angular's own benchmarks, particularly for large, frequently-updated lists — a concrete, citable performance reason to prefer it over *ngFor in new code.
@forNgForOfIterableDiffer*ngFor