0
0
AngularConceptBeginner · 3 min read

NgFor in Angular: What It Is and How to Use It

In Angular, *ngFor is a built-in structural directive used to repeat a template block for each item in a list. It simplifies rendering lists by iterating over arrays directly in the template, making UI code cleaner and more readable.
⚙️

How It Works

The *ngFor directive in Angular works like a loop inside your HTML template. Imagine you have a list of items, like a shopping list, and you want to show each item on the screen. Instead of writing HTML for each item manually, *ngFor lets Angular repeat a block of HTML for every item in your list automatically.

Think of it like a conveyor belt in a factory where each product (list item) passes by and gets wrapped (rendered) the same way. You just tell Angular to use *ngFor with your list, and it handles the rest, creating one piece of UI per item.

This directive improves readability and reduces errors because you write the template once, and Angular manages the repetition and updates efficiently when the list changes.

💻

Example

This example shows how to use *ngFor to display a list of fruits in an Angular component template.

angular
<ul>
  <li *ngFor="let fruit of fruits">{{ fruit }}</li>
</ul>
Output
<ul> <li>Apple</li> <li>Banana</li> <li>Cherry</li> </ul>
🎯

When to Use

Use *ngFor whenever you need to display a list of items dynamically in your Angular app. It is perfect for showing lists like menus, user comments, product catalogs, or any repeated content.

It helps keep your templates clean and easy to maintain, especially when the list can change over time, such as adding or removing items. Instead of manually updating the HTML, Angular updates the UI automatically.

Key Points

  • *ngFor repeats a template block for each item in a list.
  • It simplifies rendering lists and keeps templates clean.
  • Angular updates the UI automatically when the list changes.
  • Use it for menus, lists, tables, or any repeated content.

Key Takeaways

*ngFor is Angular's directive for looping over lists in templates.
It makes displaying repeated content simple and clean.
Angular handles UI updates automatically when the list changes.
Use *ngFor for any dynamic list rendering in your app.