How to Use ngFor in Angular: Syntax and Examples
Use the
*ngFor directive in Angular templates to repeat an element for each item in a list. The syntax is *ngFor="let item of items", where items is the array and item is the current element in the loop.Syntax
The *ngFor directive repeats an element for each item in a list. The basic syntax is:
let item: declares a variable for the current item.of items: specifies the array or list to loop over.
html
<div *ngFor="let item of items">{{ item }}</div>Example
This example shows how to use *ngFor to display a list of fruits in an Angular component template.
typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-fruit-list', template: ` <h3>Fruit List</h3> <ul> <li *ngFor="let fruit of fruits">{{ fruit }}</li> </ul> ` }) export class FruitListComponent { fruits = ['Apple', 'Banana', 'Cherry']; }
Output
<h3>Fruit List</h3>
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
Common Pitfalls
Common mistakes when using *ngFor include:
- Forgetting the
letkeyword before the item variable. - Using parentheses instead of quotes around the directive value.
- Not providing a unique
trackByfunction when rendering large or dynamic lists, which can hurt performance.
html
Wrong: <div *ngFor="item of items">{{ item }}</div> Right: <div *ngFor="let item of items">{{ item }}</div>
Quick Reference
| Part | Description | Example |
|---|---|---|
| let item | Declares the variable for current item | let fruit |
| of items | Specifies the array to loop over | of fruits |
| index as i | Gets current index in loop | let i = index |
| trackBy | Improves performance by tracking items | *ngFor="let item of items; trackBy: trackByFn" |
Key Takeaways
Use
*ngFor="let item of items" to loop over arrays in Angular templates.Always include the
let keyword before the item variable.Use
trackBy with large lists to optimize rendering performance.You can access the current index with
let i = index inside *ngFor.Avoid syntax errors like missing quotes or wrong keywords to ensure
*ngFor works correctly.