How to use ngFor in angular

How to use ngFor in angular

In this article lets understand how to use ngFor in angular.

In Angular, ngFor is a built-in directive used for rendering a collection of items. This way angular object and generate HTML elements for each item in the collection. The ngFor directive is commonly used in Angular templates to create dynamic lists, tables, or any other repeating elements.

Here’s the basic syntax for using ngFor in Angular:

<container-element *ngFor="let item of items; let i = index">
  <!-- Content to be repeated for each item -->

Let’s understand the syntax:

  • container-element: This is the HTML element that will contain the repeated content for each item.
  • *ngFor: It is a structural directive in Angular denoted by the asterisk * prefix. This way angular understand to iterate.
  • let item of items: This is the iteration statement. item is a local template variable that represents the current item in the iteration, and items is the array or iterable object to loop over.
  • let i = index (optional): You can also access the index of each item using the index keyword. This is useful if you need to track the position of each item in the iteration.

Here’s an example to illustrate the usage of ngFor:

let fruits = ["Apple","Banana","Orange"]
  <li *ngFor="let fruit of fruits; let i = index">{{ i + 1 }}. {{ fruit }}</li>

Output :

In this example, we have an array fruits containing different fruit names. The ngFor directive is used with an <li> element to generate a list item for each fruit. The i variable is used to display the index of each fruit item, and {{ fruit }} displays the name of the fruit.

Note: When using ngFor, make sure that the items array or iterable object is defined in the component class and accessible to the template where you’re using ngFor.

That’s the basic usage of ngFor in Angular. It’s a powerful directive that allows you to create dynamic and interactive templates based on collections of data.

That’s all about how to use ngFor in angular.

Read more articles on Angular here.