Angular 7: List Rendering with @for
easy⏱ 5 mincourseangular
@for (item of items(); track item.id)
The basic shape is @for (item of items(); track item.id) { <li>{{ item.name }}</li> }. Inside the block you also get implicit variables like $index, $first, $last, $even, and $odd for free, without declaring them yourself — handy for zebra-striping rows or numbering items.
@for (task of tasks(); track task.id) {
<li [class.done]="task.done">{{ $index + 1 }}. {{ task.title }}</li>
}
Why track is mandatory
Without a stable identity, Angular would have to guess which rendered DOM node maps to which array item every time the list changes — usually falling back to matching everything by index, which silently misattributes state (an open dropdown or an in-progress text edit can jump to the wrong row after a reorder). track item.id gives Angular a stable key so it can correctly reuse, move, or destroy exactly the right DOM nodes. It's the same rationale behind key in React, :key in Vue's v-for, and the keyed #each block in Svelte.
Build TaskList
Use @for (task of tasks(); track task.id) to render each task's title in an <li>, and add an @empty { ... } block showing "No tasks left!" when tasks() is empty. Add a completeTask(id) method that removes a task from the tasks signal.