DEV Community

Cover image for ngFor in Angular
Kavindu Karunasena
Kavindu Karunasena

Posted on

ngFor in Angular

ngFor is a built-in Angular directive that streamlines iterating over collections (arrays) in your templates. It's similar to JavaScript's for loop, but specifically designed for the world of Angular.

import { Component } from '@angular/core';

  selector: 'app-my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.css']
export class MyComponent {
  products = [
    { name: 'Apple', price: 1.99 },
    { name: 'Banana', price: 0.79 },
    { name: 'Orange', price: 2.49 }
Enter fullscreen mode Exit fullscreen mode

Inside the component class, we define an array named products containing objects with product details (name and price).

  <li *ngFor="let product of products">
    {{ }} - ${{ product.price }}

Enter fullscreen mode Exit fullscreen mode
  • Inside the list, we use *ngFor on each

  • element.
  • let product: This creates a variable named product that holds the current product object during each iteration.

  • of products: This specifies the array to iterate over, which is the products array in this case.

  • Within the

  • , we display product information using interpolation.


  1. Angular encounters *ngFor.
  2. It iterates over the products array.
  3. For each product object, it:
  • Creates a new
  • element.
  • Assigns the current product to the product variable.
  • Renders the product name and price inside the list item.

Additional Notes:

  • ngFor works with arrays of any data type, not just objects.

  • You can access object properties within the loop using dot notation (e.g.,

  • For more complex scenarios, you can use index to get the current item's position (*ngFor="let product of products; let i = index").

By using ngFor, you efficiently display dynamic content based on collections in your Angular applications.

Top comments (0)