Sub topic 4
Rendering the list with bindings and @for
This chapter assumes you have a running Angular project from the earlier chapters. It also assumes you have a Task interface with id, title and done, and that you know what a signal is at a basic level (a value you read by calling it, like tasks()). Signals are covered properly in a later chapter. Here the focus is the template: how data gets onto the page, how user actions get back out, and how @for turns an array into a list.
The working model
An Angular template is HTML with extra syntax. The compiler turns it into code that reads values from the component class and writes them to the DOM. Four binding forms cover almost everything in a task list.
| Syntax | Direction | What it does | Example |
|---|---|---|---|
| `{{ expr }}` | class to DOM | Writes the value as text | `{{ task.title }}` |
| `[prop]="expr"` | class to DOM | Sets a DOM property | `[checked]="task.done"` |
| `[class.name]="expr"` | class to DOM | Adds or removes one CSS class | `[class.done]="task.done"` |
| `(event)="stmt"` | DOM to class | Runs a statement when the event fires | `(click)="remove(task.id)"` |
Data flows down through the bracket forms. Events flow up through the parenthesis form. The handler changes state, and Angular updates the parts of the DOM that read that state.
A self-contained list component
The next chapters move the state into a service. For now, the component holds its own signals so you can run it immediately. Create task-list.component.ts:
import { Component, computed, signal } from '@angular/core';
import { Task } from './task';
@Component({
selector: 'app-task-list',
template: `
<ul>
@for (task of tasks(); track task.id) {
<li>
<input type="checkbox" [checked]="task.done" (change)="toggle(task.id)" />
<span [class.done]="task.done">{{ task.title }}</span>
<button type="button" (click)="remove(task.id)">Delete</button>
</li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
<p>{{ remaining() }} remaining</p>
`,
styles: [`.done { text-decoration: line-through; }`],
})
export class TaskListComponent {
readonly tasks = signal<Task[]>([
{ id: 1, title: 'Install the Angular CLI', done: true },
{ id: 2, title: 'Render a list', done: false },
{ id: 3, title: 'Add a form', done: false },
]);
readonly remaining = computed(() => this.tasks().filter(t => !t.done).length);
toggle(id: number): void {
this.tasks.update(list => list.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
}
remove(id: number): void {
this.tasks.update(list => list.filter(t => t.id !== id));
}
}To display it, import the component in your root component and use its selector:
import { Component } from '@angular/core';
import { TaskListComponent } from './task-list.component';
@Component({
selector: 'app-root',
imports: [TaskListComponent],
template: `<h1>Tasks</h1><app-task-list />`,
})
export class App {}Run ng serve. You should see three items, with the first one checked and struck through. Clicking a checkbox toggles the item and changes the remaining count. Clicking Delete removes the item. Delete all three and the @empty message appears.
Reading each binding
Interpolation
{{ task.title }} evaluates the expression and writes it as text. Angular escapes the value, so a title like <b>hi</b> shows as literal characters and is not parsed as HTML. Interpolation always produces text. Use it for content, not for attributes that expect booleans or numbers.
Property binding
[checked]="task.done" sets the DOM property checked to a boolean. This matters because the HTML attribute checked only sets the initial state. The property reflects the live state. The same reasoning applies to [disabled], [value] and [hidden]. If you wrote checked="{{ task.done }}", you would pass the string "false", which is truthy as an attribute value, and the box would be checked.
Class binding
[class.done]="task.done" adds the done class when the expression is truthy and removes it otherwise. It leaves other classes on the element alone, which is why it is safer than binding the whole class attribute for a single toggle.
Event binding
(change)="toggle(task.id)" runs the statement each time the checkbox's change event fires. Inside an event statement, $event holds the DOM event object. You do not need it here because the handler only needs the task id from the loop variable.
How @for works
@for is built-in control flow. It needs no import, unlike the older *ngFor directive, which required NgFor or CommonModule.
@for (task of tasks(); track task.id) {
<li>{{ task.title }}</li>
} @empty {
<li>No tasks yet.</li>
}The parts are:
taskis the loop variable, available inside the block.tasks()is the collection. It can be an array or any iterable.track task.idis a required expression that gives each item a stable identity.@emptyis an optional block rendered when the collection has no items.
Why track is required
When the array changes, Angular must decide which existing DOM nodes to keep, move, create or destroy. The track expression is the key it uses to match old items to new ones. With track task.id, toggling one task creates a new object for that task, but the id is the same. Angular reuses the existing <li> and updates only the bindings that changed. Focus, scroll position and any text the user typed into that row survive.
If you track by object identity instead (track task), every immutable update creates a new object. Angular then sees a different key and destroys and recreates that row's DOM. That is correct output but wasted work, and it loses element state.
Use a stable unique value from the data, such as an id. Use track $index only for lists that are never reordered or filtered, or for primitive values with no identity.
Contextual variables
Inside the block you also get these variables:
| Variable | Meaning |
|---|---|
| `$index` | Zero-based position of the current item |
| `$count` | Total number of items |
| `$first`, `$last` | True for the first or last item |
| `$even`, `$odd` | True for even or odd positions |
You can alias them with let:
@for (task of tasks(); track task.id; let i = $index, last = $last) {
<li [class.last]="last">{{ i + 1 }}. {{ task.title }}</li>
}Conditional blocks in the same template
@if and @else follow the same style and are often used next to @for:
@if (remaining() === 0) {
<p>All done.</p>
} @else {
<p>{{ remaining() }} remaining</p>
}Common errors
The mistakes below come up most often with this chapter's code.
- Omitting
track. The compiler rejects an@forblock without a track expression. Addtrack task.id. - Duplicate track values. If two tasks share an id, Angular warns in development mode and may reuse the wrong DOM node. Make sure ids are unique, which is why the service later uses an incrementing counter.
- Mutating the array in place. Calling
this.tasks().push(newTask)changes the array but does not notify the signal, so the view may not update. Always replace the array withupdate()orset(), astoggle()andremove()do above. - Binding a string where a boolean is needed. Use
[disabled]="form.invalid", notdisabled="{{ form.invalid }}". - Writing
[attr.checked]. This sets the attribute, not the live property, so the checkbox may not follow later changes. Use[checked]. - Literal
@or braces in template text. The characters@,{and}start control flow syntax. To show an email address like[email protected], writeteam@example.com. To show a literal}, write}. - Handlers that do too much. Template expressions run often. Keep them to simple reads and method calls. Put derived values in
computed(), asremainingdoes, instead of filtering inside the template.
Edge cases
- Filtered or sorted views. If you later render
visibleTasks()from acomputed(), keep tracking bytask.id. Tracking by$indexwould make Angular reuse rows by position, so the wrong row could keep a checked state. - Empty versus loading.
@emptyonly knows the collection is empty. It cannot tell "no tasks" from "still loading". When you add HTTP loading in a later chapter, use a separate@iffor the loading state. - Large lists. Stable tracking keeps updates cheap, but rendering thousands of rows still costs memory. At that scale, consider pagination or virtual scrolling.
Exercise
A teammate changes the loop to @for (task of tasks(); track task) and notices that checking a box makes the row lose keyboard focus. Why does this happen, and what is the fix?
Show answer
Each toggle replaces the task object with a new copy ({ ...t, done: !t.done }). Tracking by the object means Angular sees a different key, so it destroys the old <li> and builds a new one, and the focused checkbox is gone. Tracking by task.id keeps the key stable, so Angular reuses the same element and only updates the changed bindings. The fix is track task.id.
Exercise
Extend the template so that the first item shows the text "(next up)" after its title, and the row for every odd position gets a CSS class stripe. Which two constructs do you use, and where do they go?
Show answer
Alias the contextual variables in the @for header, or use them directly. Inside the <li>, add [class.stripe]="$odd" for the stripe, and add @if ($first) { <em>(next up)</em> } after the title span. No imports are needed, because $odd, $first and @if are all part of the built-in control flow.