What is the use of ngFor directive in Angular?

Angular ngFor directive is used in a template to display each item in a list. For example, here we iterate over list of users,

  • {{ user }}

The user variable in the ngFor double-quoted instruction is a template input variable.

The ngFor directive in Angular is used for rendering lists of data by iterating over an array or an iterable object. It allows you to loop through each item in the array and generate corresponding HTML elements for each item. This is particularly useful for displaying dynamic content, such as a list of items fetched from a database or received from an API.

Here’s a breakdown of its main functionalities:

  1. Iterating over Arrays: ngFor can loop through arrays and display each item.
    html
    <div *ngFor="let item of items">
    {{ item }}
    </div>
  2. Iterating over Objects: It can also loop through objects and access key-value pairs.
    html
    <div *ngFor="let key of keys()">
    {{ key }}: {{ items[key] }}
    </div>
  3. Tracking Changes: ngFor tracks changes to the array or iterable and efficiently updates the DOM when items are added, removed, or re-ordered. This improves performance by avoiding unnecessary re-rendering of unchanged items.
    html
    <div *ngFor="let item of items; trackBy: trackByFn">
    {{ item }}
    </div>
    typescript
    trackByFn(index, item) {
    return item.id; // unique identifier for each item
    }
  4. Template Variables: It provides access to the index of the current item, as well as a few other built-in variables.
    html
    <div *ngFor="let item of items; let i = index">
    {{ i }}: {{ item }}
    </div>

In summary, ngFor is a powerful directive in Angular for dynamically rendering lists of data, providing flexibility and efficiency in managing and displaying data-driven content.