*ngFor helps you show many items on the screen by repeating a template for each item in a list. It saves time and keeps your code clean.
0
0
*ngFor for list rendering in Angular
Introduction
You want to show a list of names or products on a webpage.
You have an array of messages and want to display each message in a chat app.
You want to create a menu where each option comes from a list.
You need to display a list of tasks or to-dos dynamically.
You want to show a gallery of images from an array of image URLs.
Syntax
Angular
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>The *ngFor directive repeats the <li> element for each item in the items array.
let item creates a variable for each element in the list during the loop.
Examples
Shows a list of fruits from the
fruits array.Angular
<ul>
<li *ngFor="let fruit of fruits">{{ fruit }}</li>
</ul>Shows a numbered list of user names using the index.
Angular
<ul> <li *ngFor="let user of users; index as i">{{ i + 1 }}. {{ user.name }}</li> </ul>
Uses
trackBy to optimize rendering when the list changes.Angular
<ul>
<li *ngFor="let color of colors; trackBy: trackByColor">{{ color }}</li>
</ul>If the list is empty, nothing is shown because
*ngFor does not render any elements.Angular
<ul>
<li *ngFor="let item of emptyList">No items found.</li>
</ul>Sample Program
This component shows a heading and a list of fruits. The *ngFor repeats the <li> for each fruit in the fruits array.
Angular
import { Component } from '@angular/core'; @Component({ selector: 'app-fruit-list', template: ` <h2>Fruit List</h2> <ul> <li *ngFor="let fruit of fruits">{{ fruit }}</li> </ul> ` }) export class FruitListComponent { fruits = ['Apple', 'Banana', 'Cherry']; }
OutputSuccess
Important Notes
Time complexity: Rendering takes time proportional to the number of items in the list.
Space complexity: Uses space for each repeated element in the DOM.
Common mistake: forgetting to use let before the variable name in *ngFor.
Use *ngFor when you want to display lists dynamically. For static content, just write HTML directly.
Summary
*ngFor repeats a template for each item in a list.
Use let item of items to access each element.
It helps keep your HTML clean and dynamic.