NgFor Directive in Angular

By | | Updated : 2019-11-30 | Viewed : 270 times

NgFor Directive Introduction

One of the Structural and builtin directives provided in Angular. Here the current article will explain the NgFor directive with examples in Angular.

NgFor Directive

To display the data as and in tables/Lists in the HTML template we should go for NgFor directive in Angular. The core Structural directive used for the Iteration of Arrays/List. So here Each item will be displayed through iteration.

Using of NgFor

Let's consider the programming language list which is for displaying the data in the view of the HTML template.

Programming List for NgFor
  languageList: [] = [
    new Language(1, 'C'),
    new Language(2, 'C++'),
    new Language(3, 'Java'),
    new Language(4, '.Net'),
    new Language(5, 'Python')  

This is an Array variable for iterating through NgFor directive. Each item will be populated on every iteration of LanguageList. So NgFor directive will be very useful to display the data in the HTML template while iterating the Array/Lists type of data in Angular. Please have a look into the below-given code snippet.

Syntax of NgFor

Syntax for NgFor
<table style="color: #26a69a;border-top: #26a69a solid 1px;border-bottom: #26a69a solid 1px;">
	<thead >
	<th style="color: #26a69a;width:25%;">Index</th>
	<th style="padding-left: 25%;">Name</th>
		<tr *ngFor="let language of myLanguageList;">
			<td style="color: #26a69a;">{{language.index}}</td>
			<td style="color: #26a69a;padding-left: 35%;">{{}}</td>

So here we used the *ngFor directive with expression. The expression is like "let language of LanguageList;". language is used for looping of LanguageList. Here language will be looped and displayed in each iteration.

Let's write code for the component which will be used to display the programming languages in the HTML.

import { Component, OnInit } from '@angular/core';
import { Language }            	from '../language';

  selector: 'app-languages',
  templateUrl: './languages.component.html',
  styles: []
export class LanguagesComponent implements OnInit {
  constructor() {}

  ngOnInit() {
  languageList = [
    new Language(1, 'C'),
    new Language(2, 'C++'),
    new Language(3, 'Java'),
    new Language(4, '.Net'),
    new Language(5, 'Python')  
    myLanguageList = this.languageList;

Highlights of NgFor Syntax:

In the NgFor directive, we used the expression which consists of Array/List.

Observe the expression in the above example "let language of LanguageList;"

The variable language defined with keyword let. On each iteration, one of Item in Array/List will be assigned to the language and it will be represented as a current item in the loop.

On each iteration, the Arrays/Lists will give the item to display. Here the iteration will be working as Javascript for loop iteration only.

Note: the Variable language will not be accessed outside of the ngFor directive as a language variable related to the ngFor directive.

Item Index in NgFor

Please see the below-given example for getting an index of the element in the NgFor directive.

Using of Index of NgFor
<tr *ngFor="let language of myLanguageList;let i = index;">
	<td style="color: #26a69a;padding-left: 15%;">{{language.type}}</td>
	<td style="color: #26a69a;padding-left: 20%;">{{}}</td>

Here we used the let keyword with i variable to get the index of the Array/List in Angular.

Without using the let keyword if we try to get the index from the Array/List we will get an error message.

First/Last index in NgFor

Some times we will be having a requirement to apply some special operations like applying a style to the first and last elements of Array/Lists. So here it is required to use the first/last index of NgFor.

Example for First/Last Item in NgFor
<tr *ngFor="let language of myLanguageList;let i = index;let first = first;let last = last;" >
	<td style="padding-left: 12%;" [ngClass]="{ first: first, last: last }">{{i}}</td>
	<td style="padding-left: 10%;" [ngClass]="{ first: first, last: last }">{{language.type}}</td>
	<td style="padding-left: 10%;" [ngClass]="{ first: first, last: last }">{{}}</td>

Here CSS classes first/last will be applied on the first/last elements of Array/Lists.

Item Index in NgFor
<tr *ngFor="let language of myLanguageList;let i = index;let even = even; let odd = odd;" >
	<td style="padding-left: 12%;" [ngClass]="{ odd: odd, even: even }">{{i}}</td>
	<td style="padding-left: 10%;" [ngClass]="{ odd: odd, even: even }">{{language.type}}</td>
	<td style="padding-left: 10%;" [ngClass]="{ odd: odd, even: even }">{{}}</td>

You may see some of the table rows by applying the color style of alternative rows. So to achieve the same we should go for even/odd indexes of elements. Please see the below-given example with the use of even/odd indexes of NgFor.

Even/Odd index in NgFor

Note: After loading of new Array/List, NgFor will not reload the entire list by removing/adding the existing element from the DOM.

Using of Tracked by

In ngFor Directive, the Array/List tracked by the Item Node, not with item identity. If we create a new list with the same values as a previously passed item list to the ngFor. Angular is not able to identify the newly constructed list. To identify item node NgFor directive will call and tracked by function and will use the result.

Importance of trackby

Removing and adding the entire biggest list into dom will lead to the performance problem. Please find the entire example for trackBy.

Example for trackBy in NgFor
   template: `
   <tr *ngFor="let language of LanguageList;trackBy:trackByLangid">
   <td>{{language .index}}</td>
   <td>{{language .name}}</td>
   export class LanguagesComponet{   
        languageList	= languageList; 
        language		= languageList[0];   
   	trackByLangid(index: number,  language:  Language): number { 		return; }
Leave A Reply