ngFor Directive
Imagine you have a shopping list. Instead of writing each item manually, you have a magical list that automatically generates each item. Angular's *ngFor directive does exactly that – it repeats a template for each item in a list.
The *ngFor directive is a structural directive that renders a template for each item in a collection.
Basic syntax:
<li *ngFor="let item of items">
{{ item }}
</li>
Here's a complete example:
@Component({
selector: 'app-todo-list',
template: `
<h2>My Todo List</h2>
<ul>
<li *ngFor="let todo of todos; let i = index">
{{ i + 1 }}. {{ todo }}
<button (click)="removeTodo(i)">Remove</button>
</li>
</ul>
<input #newTodo placeholder="Add new todo">
<button (click)="addTodo(newTodo.value); newTodo.value=''">Add</button>
`
})
export class TodoListComponent {
todos = ['Learn Angular', 'Build an app', 'Deploy to production'];
addTodo(todo: string) {
if (todo.trim()) {
this.todos.push(todo);
}
}
removeTodo(index: number) {
this.todos.splice(index, 1);
}
}
*ngFor provides several helpful variables:
<li *ngFor="let item of items; let i = index; let isFirst = first; let isLast = last; let isEven = even; let isOdd = odd">
{{ i }} - {{ item }} - First: {{ isFirst }} - Last: {{ isLast }} - Even: {{ isEven }} - Odd: {{ isOdd }}
</li>
For better performance, always use
trackBy with *ngFor:<li *ngFor="let item of items; trackBy: trackById">
{{ item.name }}
</li>
trackById(index: number, item: any) {
return item.id;
}
Two Minute Drill
- *ngFor repeats a template for each item in an array.
- Syntax: `*ngFor="let item of items"`.
- Access index, first, last, even, odd properties.
- Always use `trackBy` for performance with large lists.
- Perfect for displaying lists, tables, dropdowns.
Need more clarification?
Drop us an email at career@quipoinfotech.com
