Back to course

Built-in Structural Directives: *NgFor

The Complete Angular Developer: From Zero to Hero

16. Built-in Structural Directives: *NgFor

*NgFor is used to iterate over a collection (like an array) and render a template once for each item in that collection.

Simple Iteration

Component Class:

typescript interface Product { id: number; name: string; price: number; }

export class ProductListComponent { products: Product[] = [ { id: 1, name: 'Laptop', price: 1200 }, { id: 2, name: 'Mouse', price: 25 }, { id: 3, name: 'Keyboard', price: 75 } ]; }

Template:

html

  • ID: {{ product.id }} | Name: {{ product.name }} | Price: ${{ product.price }}

Exported Local Variables

*NgFor exposes several local variables that provide information about the iteration status:

VariableValue
indexThe current index of the item (0-based)
firstBoolean, true if the item is the first in the array
lastBoolean, true if the item is the last in the array
evenBoolean, true if the index is even
oddBoolean, true if the index is odd

Example using index and class binding:

html

  • ({{ i + 1 }}) {{ item.name }}

The trackBy Function (Performance)

When the data source changes (e.g., an item is added, removed, or reordered), Angular rebuilds the entire DOM tree for the list by default. This is inefficient.

trackBy tells Angular how to uniquely identify each item. If the identity (e.g., the product ID) has not changed, Angular reuses the existing DOM element.

typescript trackProductById(index: number, product: Product): number { return product.id; }

html

  • {{ item.name }}