0
0
AngularHow-ToBeginner · 3 min read

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 let keyword before the item variable.
  • Using parentheses instead of quotes around the directive value.
  • Not providing a unique trackBy function 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

PartDescriptionExample
let itemDeclares the variable for current itemlet fruit
of itemsSpecifies the array to loop overof fruits
index as iGets current index in looplet i = index
trackByImproves 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.