Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Angular ngFor Directive: The Ultimate Guide

angular ngFor example

Angular is a popular open-source web application framework used to simplify the development of single-page applications. One of Angular’s most powerful features is the use of directives, which allow developers to manipulate the DOM with ease. Among these directives, ngFor is an essential tool for iterating over collections and rendering elements dynamically.

With the release of Angular 18, there are several updates and enhancements that further improve the usage of ngFor. In this article, we’ll explore the latest features and best practices for using ngFor in Angular 18.

Understanding Angular ngFor

Angular provides several built-in directives, including ngIf, ngFor, ngSwitch, ngClass, and ngStyle. The first three directives are structural directives, which are responsible for changing the layout of the HTML by adding, removing, or modifying elements from the DOM. Structural directives start with an asterisk ( * ). The last two directives, ngClass and ngStyle, manipulate the appearance of the DOM elements and are called attribute directives. They start with [] square brackets.

The ngFor directive is similar to the traditional for loop in JavaScript but is designed to work seamlessly with Angular’s change detection and template system. It allows developers to iterate over an array or list and render the corresponding HTML elements for each item. The syntax is straightforward:

Syntax of ngFor Directive

<div *ngFor="let item of frameworks">
  <p>{{item}}</p>
</div>

Example of *ngFor directive

Here we have demonstrate an simple example to display list of framworks in component template. In this example, items is an array, and for each item in the array, the directive will create a div element and display the item’s value. The let keyword is used to declare a local variable that holds the current item from the array during each iteration.

<!-- app.component.html -->

<div *ngFor="let item of frameworks">
  <p>{{item}}</p>
</div>

<router-outlet />

<!-- app.component.ts file -->
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
  imports: [RouterOutlet, CommonModule],
})
export class AppComponent {
  title = 'mine-18';
  frameworks: string[] = ['Angular', 'Reactjs', 'Vue'];
}

In order to use the ngFor directive in an Angular component, you need to import the CommonModule from @angular/common in the module that declares the component.

The CommonModule is a module that provides common directives and pipes that are used frequently in Angular applications. It includes the NgForOf directive, which is used to implement the *ngFor structural directive.

How *ngFor directive works?

To do this, we will use *ngFor directive, here what we did

  • Need to import CommonModule in component ts file
  • iterate over a list of items in template
  • generate a new tag for each one.

Angular ngFor example basic

In Angular, the *ngFor directive is a powerful tool for iterating over a list of items and rendering each item in the template. Let’s look at two practical examples to understand its usage.

Example 1: Displaying a List of Countries

The first example demonstrates how to display a list of countries. By using *ngFor, we can loop through an array of country names and render each one within a <div> element:

Angular ngFor example
<section>
  <h4>Angular *ngFor directive example 1</h4>
  <div *ngFor="let country of ['India','France','Japan']">
   {{ country }}
  </div>
</section>

<section>
  <h4>Iterate edupala.com three times</h4>
  <div *ngFor="let site of [1,2,3]">
    Site name: edupala.com
  </div>
</section>

Example 2: Iterating a Fixed Number of Times

In the second example, we use *ngFor to iterate a fixed number of times. This can be useful for repeating a block of HTML multiple times. For instance, if we want to display the site name “edupala.com” three times, we can do the following:

We can give any name to *ngFor individual local item names, we had given country and site name in our example.

The ngFor index example

In Angular, using the index variable in the *ngFor directive is not related to performance optimization like in React. Instead, it is used to access the current iteration index of the loop.

In the example you provided, the index as i syntax is used to create a local template variable i that holds the current iteration index. The i+1 expression is then used to display the index value starting from 1 instead of 0.

  frameworks: string[] = ['Angular', 'Reactjs', 'Vue'];
Angular ngFor index
<section>
  <h4>Angular NgFor index example</h4>
  <div *ngFor="let framework of frameworks; index as i">
    {{ i+1 }} - {{ framework }}
  </div>
</section>

We can also use ngFor directive with Angular select option input,

Angular ngFor select option
<h4>Select option</h4>
<select [(ngModel)]="selected" name="valueCheck" (change)="valueChange($event)">
    <option *ngFor="let framework of frameworks" [value]="framework" [selected]="framework == selected">
      {{ framework }}
    </option>
  </select>

  <h3>{{ selected }} </h3>

In Angular versions before 14, having an app component without a module wouldn’t work as expected. However, with Angular 14 and later, you can leverage the new concept of standalone components.

Here’s how to use ngModel with a select element in a standalone component in Angular 14 or later, we can directly import FormsModule inside the app.component as below.

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
  imports: [CommonModule, FormsModule],
})
export class AppComponent {
  frameworks = ['Angular', 'React', 'Vue.js', 'Svelte'];
  selected: string = 'Angular';

  valueChange(event: any) {
    this.selected = event.target.value;
    console.log('Selected framework:', this.selected);
  }
}

Angular ngFor directive with method

In all the above examples we have used ngFor directive with array object directly, we can also use ngFor with the method, a method that returns an array object.

<h4>NgFor using method</h4>
<div *ngFor="let item of getFrameworks(); let i = index">
    {{ i+1 }} - {{ item }}
</div>

//Where getFrameworks() return
 frameworks: string[] = ['Angular', 'Reactjs', 'Vue'];
  getFrameworks(): string[] {
    return this.frameworks;
  }

The ngFor local variable even and odd example

We have learned that *ngFor directive has an index as a local variable, it also has many local variables like even and odd element indexes. In this example, we will style different for even and odd element indexes. Here is a screenshot of our example.

Angular ngFor even and odd index
<section>
 <h4>NgFor with even and odd local variables </h4>
 <div *ngFor="let number of [1,2,3,4,5,6,7,8]; odd as isOdd; even as isEven">
  <p [ngClass]="{even: isEven, odd: isOdd}">
     {{ number }}
  </p>
 </div>
</section>

We have used ngClass non-structure directive to apply CSS class name even and odd respectively for even and odd element index. Let’s add CSS style for it.

.even {
  padding:2px;
  color: white;
  background-color: blue;
}
      
.odd {
   padding:2px;
   background-color: red;
   color: white;
}

The ngFor first local variable

Like even and odd element index, we have first and last local variables to the first and last element in a collection of ngFor directives.

  <div *ngFor="let item of items; index as i; first as isFirst">
    {{ i+1 }} -
    <span *ngIf="isFirst">First Element {{ item }}</span>
    <span *ngIf="!isFirst">{{ item }}</span>
  </div>

The ngFor local varaibles

We have demonstrated a few examples of local variables of ngFor directive. Here we had listed some of these local variables used in the ngFor directive.

Local variableDescription
index: numberThe index of the current item in the iterable.
count: numberThe index of the current item in the iterable.
even: booleana boolean that is true if the element has an even index.
odd: booleana boolean that is true if the element has an odd index.
first: booleana boolean that is true if the element is the first of the collection.
last: booleana boolean that is true if the element is the last of the collection

Using these local variables can help you to perform various operations on the items being iterated over, such as applying different styles or classes to even or odd items, or displaying the index of each item.

Key Features of ngFor in Angular 18

  1. TrackBy Function

One of the significant updates in Angular 18 is the enhanced support for the trackBy function, which is used to optimize performance. By default, Angular identifies items in the list by their object references. However, in cases where the list items are frequently updated or reordered, this can lead to inefficiencies. The trackBy function allows developers to specify a unique identifier for each item, minimizing unnecessary DOM manipulations:

<div *ngFor="let name of frameworks; trackBy: trackByFn">{{ name }}</div>

  trackByFn(index: number, item: any): number {
    return item.id; // or any unique identifier
  }
  1. Enhanced Template Context

Angular 18 introduces improvements to the template context within ngFor. Developers can now access additional properties, such as the index of the current iteration, the first and last items, and even whether the current item is odd or even:

<div *ngFor="let item of frameworks; let i = index; let isOdd = odd"> 
  <p>{{ i }}: {{ item }} - Odd: {{ isOdd }}</p> 
</div>

<div *ngFor="let item of frameworks; index as i; first as isFirst; last as isLast; even as isEven; odd as isOdd"> 
  <p>{{ i }}: {{ item }} - First: {{ isFirst }} - Last: {{ isLast }} - Even: {{ isEven }} - Odd: {{ isOdd }}</p>
</div>

Conclusion
We have learned the Angular *ngFor directive and demonstrated a few examples of it with the index local variable. I hope you got some idea of how we can use this directive.The ngFor directive remains a cornerstone of Angular’s powerful template system, enabling dynamic and efficient rendering of lists. With the latest enhancements in Angular 18, developers can leverage features like the trackBy function, additional template context properties, seamless integration with asynchronous data sources, and new directives like NgForOf and NgForTrackBy to build more performant and maintainable applications. Whether you’re a seasoned Angular developer or just starting, mastering ngFor is crucial for creating dynamic and responsive web applications.

Related posts

Angular ngFor Directive: The Ultimate Guide

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top