Angular › Directives
What is the ngFor structural directive used for, and how does the newer at for syntax compare to it?
BeginnerAnswer
ngFor, and its newer replacement the at for control flow block, repeats a piece of template content once for every item in a list, letting you display a collection of data such as a list of products or names, with the newer syntax additionally requiring a track expression to help Angular efficiently update the list.
@Component({
selector: 'app-todo-list',
template: `
@for (todo of todos; track todo.id) {
<li>{{ todo.text }}</li>
}
`
})
export class TodoListComponent {
todos = [{ id: 1, text: 'Buy milk' }, { id: 2, text: 'Walk the dog' }];
}Real-world example A to do list app displays every task using the newer at for syntax, tracking each item by its unique id so Angular can efficiently update the list even as tasks are added or removed.