FOR Control Block
1. Preparing the Data Model
First, let's update our component with a list of speakers. We will use a Speaker interface to maintain type safety.
speaker-list.component.ts
TypeScript
2. Rendering Lists with @for
The @for block is essentially the JavaScript for...of loop tailored for HTML. It allows you to define a placeholder for each item and render a template for it.
speaker-list.component.html
HTML
Why is track mandatory?
In the new @for block, the track property is required. It tells Angular which unique property (like an id) it should use to identify each item.
- Performance: If the list changes, Angular only re-renders the items that actually changed rather than the entire list.
- DOM Stability: It prevents losing focus or state in input fields within a list when the array is updated.
3. Handling Empty States with @empty
In the past, we had to use an extra *ngIf to check if a list was empty. Now, the @for block comes with a built-in @empty section that renders automatically when the array length is zero.
HTML
4. Using Contextual Variables
Angular provides several "helper" variables within the loop to give you more control over the UI, such as indexing or identifying the first/last items.
$index: Current item index.$count: Total number of items.$first/$last: Boolean for the first or last item.$even/$odd: Boolean for even or odd rows (perfect for zebra-striping).
Example using aliases:
HTML
5. Modern @for vs. Legacy *ngFor
If you are coming from an older Angular project, you might be familiar with *ngFor. Here is why the new syntax is superior:
| Feature | Legacy *ngFor | Modern @for |
| Syntax | Micro-syntax string: *ngFor="..." | Built-in block: @for (...) { } |
| Performance | Optional trackBy function | Required track (Optimized by default) |
| Empty State | Requires separate *ngIf | Built-in @empty block |
| Imports | Requires CommonModule | Built-in (No imports needed in Standalone) |