×
☰ See All Chapters

Angular ngFor Directive

The HTML element in which ngFor is used will be displayed multiple times for each of the item of the collection. We can use this variable anywhere inside our template.

Syntax:

<li *ngFor="let iteratorName of collection;”> …. </li>

iteratorName is a local variable which receives the value from collection one after the other. Number of iterations is equal to the size of the collection.

Angular ngFor Directive Example

Suppose numArray equals [10, 11, 12]. The following markup creates a list element for each element in numArray. Each list element uses the num variable to access the corresponding value of numArray.

app.component.ts

import { Component } from '@angular/core';

 

@Component({

        selector: 'app-tag',

        template: ` <ul>

                        <li *ngFor='let num of numArray'>

                                Array element: {{ num }}

                        </li>

                    </ul>

                   `

})

export class AppComponent {

        numArray = [10, 11, 12];

}

 

app.module.ts

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

 

@NgModule({

  declarations: [

      AppComponent

  ],

  imports: [

    BrowserModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

index.html

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>Angular Example</title>

  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">

</head>

<body>

  <app-tag></app-tag>

</body>

</html>

Output

angular-ngfor-directive-0
 

Local Variables in ngFor

ngFor also provides several values to help us manipulate the collection. We can assign the values of these exported values to the local variable and use it in our template.

Below is the list of exported values provided by ngFor directive.

  • index : Provides the index of the current value, starting with 0 

  • first : A boolean that identifies whether the current value is the first value 

  • last : A boolean that identifies whether the current value is the last value 

  • even : A boolean that identifies whether the current value has an even index 

  • odd : A boolean that identifies whether the current value has an odd index 

To Access exported values, create additional local variable using let, and assign desired exported value.

<li *ngFor="let item of items; let i=index;”> …. </li>

Example:

To clarify how these are used, the following loop creates a paragraph for each value of numArray. The index of each value is accessed as i and l is set to a boolean that identifies whether the current value is the last value:

import { Component } from '@angular/core';

 

@Component({

        selector: 'app-tag',

        template: `<p *ngFor='let n of numArray; let i = index; let l = last'>

                    The current index is {{ i }}. Last value? {{ l }}

                   </p>

                   `

})

export class AppComponent {

        numArray = [10, 11, 12];

}

 

If numArray contains three values, the output will be displayed as follows:

angular-ngfor-directive-1
 

Angular ngFor directive trackBy

Track By clause allows you to specify your own key to identify objects. Angular generates unique IDs for each item in your collection to track the items collection. This has a huge performance implication. For instance, consider you have items in your DOM and want to refresh them with the new items from the database. Although the retrieved items are similar to those available in the DOM, the Angular have no means to identify them. The Angular simply remove these elements from DOM and recreates the new elements from the new data.

trackBy clause eliminates this problem, by telling angular how to identify the similar elements. The Angular will use the value returned by trackBy to match the elements returned by the database and updates the DOM Elements without recreating them. To use trackBy NgFor needs to be associated with a tracking function. This function receives the index of each element and the element itself. This function should return a value which should be unique across the application. So while returning value careful about maintaining unique value. The value returned will be used as id for the HTML element of your collection to track the items collection.

Angular ngFor directive trackBy Example

app.component.ts

import { Component } from '@angular/core';

 

@Component({

    selector: 'app-tag',

    template: `<p *ngFor="let movie of employees; trackBy:trackThing;">

                    Name : {{movie.name}}, ID : {{movie.id}}

              </p>`

})

 

export class AppComponent

{

    employees: Employee[] =[

        {name:'Manu Manjunatha',id:'100'},

        {name:'Advith',id:'200'},

        {name:'Likitha',id:'300'},

    ]

       

        trackThing (index, item){

                return item.title + item.director ;

        }

}

 

class Employee {

    name : string;

    id : string;

}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

 

@NgModule({

  declarations: [

      AppComponent

  ],

  imports: [

    BrowserModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

index.html

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>Angular Example</title>

  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">

</head>

<body>

  <app-tag></app-tag>

</body>

</html>

Output

angular-ngfor-directive-2
 

All Chapters
Author