Skip to main content

ngFor

ngFor is a built-in structural directive in Angular that is used to loop over a collection of items and create a template for each item in the list. It's commonly used to display dynamic data in the form of lists or tables in Angular applications.

Basic Usage of ngFor

The syntax for ngFor is *ngFor="let item of collection", where collection is the iterable list (an array or something similar) and item is a template input variable that represents the current item in each iteration.

Example:

Assume you have an array of names in your component:

@Component({
selector: 'app-example',
template: `
<ul>
<li *ngFor="let froot of froots">{{ froot }}</li>
</ul>
`
})
export class ExampleComponent {
froots = ['Banana', 'Mango', 'Orange'];
}

In this example, ngFor iterates over the froots array. For each element in the array, it creates a new <li> element in the DOM, setting the content of that element to the current item (froot).

Key Features

  1. Tracking By Function:--

    • Angular can track items in the list with a custom tracking function, which is useful for optimizing performance, especially with large lists.
    • The tracking function takes the index and the current item as arguments and should return a unique identifier for each item.
    trackByFn(index, item) {
    return item.id; // or some other unique property
    }

    Used in the template as:

    <div *ngFor="let item of colections; trackBy: trackByFn">{{ item.name }}</div>
  2. Local Variables Inside ngFor:

    • ngFor provides several local variables that can be used in the template:
      • index:-- the index of the current item in the iterable.
      • first:-- a boolean indicating if the item is the first item in the iterable.
      • last:-- a boolean indicating if the item is the last item in the iterable.
      • even:-- a boolean indicating if the item is on an even index.
      • odd:-- a boolean indicating if the item is on an odd index.

    Example:

    <div *ngFor="let item of items; let i = index">
    {{ i }}: {{ item.name }}
    </div>

More Examples

Here are various examples illustrating different uses and features of ngFor:

Basic Looping

  1. Simple List Rendering: Displaying each item in an array as a list element.

    <ul>
    <li *ngFor="let item of items">{{ item }}</li>
    </ul>

    This will render a list (<li>) element for each item in the items array.

Index, First, Last, Even, Odd

  1. Using Local Variables: ngFor provides local variables like index, first, last, even, and odd.

    <div *ngFor="let item of items; let i = index; let isEven = even">
    {{ i }}: {{ item }} - {{ isEven ? 'Even' : 'Odd' }}
    </div>

    This displays each item with its index and specifies if it's in an even or odd position.

TrackBy Function

  1. Optimization with trackBy: Using trackBy to improve performance by tracking items with a unique identifier.

    trackByItems(index: number, item: any): number {
    return item.id; // or any unique property of `item`
    }
    <div *ngFor="let item of items; trackBy: trackByItems">
    {{ item.name }}
    </div>

    This is beneficial for large lists and lists that change frequently, as it helps Angular keep track of which items have changed.

Nested Loops

  1. Nested ngFor Loops: Rendering a list within another list.

    <ul>
    <li *ngFor="let user of users">
    {{ user.name }}
    <ul>
    <li *ngFor="let friend of user.friends">{{ friend }}</li>
    </ul>
    </li>
    </ul>

    This example loops over users and, for each user, loops over their friends.

Tables and Grids

  1. Creating Tables or Grids: Using ngFor to dynamically create rows and columns in a table or grid.

    <table>
    <tr *ngFor="let row of tableData">
    <td *ngFor="let cell of row">{{ cell }}</td>
    </tr>
    </table>

    This will create a table based on the multi-dimensional array tableData.

Conditional Looping with ng-container

  1. Conditional Looping: Using ngFor with ng-container to apply a condition to each item.

    <ng-container *ngFor="let item of items">
    <div *ngIf="item.isActive">{{ item.name }}</div>
    </ng-container>

    This renders div elements only for items where isActive is true.

Dynamic Component Rendering

  1. Dynamic Components: Using ngFor to dynamically create components.

    <ng-container *ngFor="let item of dynamicComponents">
    <ng-container *ngComponentOutlet="item.component"></ng-container>
    </ng-container>

Best Practices

  • Use trackBy When Appropriate:-- Especially with lists that may change dynamically. It can significantly improve performance.
  • Avoid Complex Logic in Templates:-- Keep the template syntax simple and delegate complex logic to the component class.
  • Be Mindful of Changes:-- Remember that ngFor operates on the reference of the array. Changing the content of the array without changing the reference might not trigger a UI update.

Use Cases

  • Displaying Lists:-- From simple lists to complex structures like tables and grids.
  • Rendering Multiple Components:-- Dynamically creating a series of child components based on a data array.
  • Data Presentations:-- In conjunction with other directives and Angular Material components for richer data presentation.