Angular Series #2 — ngFor & ngFor trackBy

Vaibhav Bhapkar
3 min readApr 10, 2020

--

In this article, we will see how we can use ngFor in angular and what is the difference between ngFor and ngFor trackBy,

ngFor:

The structural directive in angular is responsible for HTML layout they shape and reshape DOM structure typically by adding, removing and manipulating elements. ngFor is a directive that helps you to iterate over data. Let’s look into an example of NgFor,

employee-detail.component.ts

import { Component, OnInit } from ‘@angular/core’;@Component({selector: ‘app-employee-details’,templateUrl: ‘./employee-details.component.html’,styleUrls: [‘./employee-details.component.css’]})export class EmployeeDetailsComponent implements OnInit {constructor() { }ngOnInit() {}employees:any[]=[{empid:’1',name:’Vaibhav’},{empid:’2',name:’Employee1'},{empid:’3',name:’Employee2'}]}

employee-detail.component.html

<table><thead><tr><th>Employee ID</th><th>Employee Name</th></tr></thead><tbody><! — employees property contains array elemt of employees which defined in TS fileemployee is template input variable which is accessible by tr element and any of its child element --><tr *ngFor=”let employee of employees”><td>{{employee.empid}}</td><td>{{employee.name}}</td></tr></tbody></table>

ngFor trackBy:

ngFor typically used to iterate over list of items with the small list we can use ngFor but for a large list, ngFor will perform poorly. A small change in list cascade a DOM manipulation and may lead to performance issues. Let’s look into an example which will show how angular will act element addition with ngFor,

employee-detail.component.ts

import { Component, OnInit } from ‘@angular/core’;@Component({selector: ‘app-employee-details’,templateUrl: ‘./employee-details.component.html’,styleUrls: [‘./employee-details.component.css’]})export class EmployeeDetailsComponent implements OnInit {employees:any[];constructor() {this.employees=[{empid:’1',name:’Vaibhav’},{empid:’2',name:’Employee1'},{empid:’3',name:’Employee2'}];}ngOnInit() {}getEmployee():void{this.employees=[{empid:’1',name:’Vaibhav’},{empid:’2',name:’Employee1'},{empid:’3',name:’Employee2'},{empid:’4',name:’Employee3'}];}}

employee-detail.component.html

<table><thead><tr><th>Employee ID</th><th>Employee Name</th></tr></thead><tbody><tr *ngFor=”let employee of employees”><td>{{employee.empid}}</td><td>{{employee.name}}</td></tr></tbody></table><br/><button (click)=”getEmployee()”>Refresh List</button>

Here, when you look into this example we have created one method which includes one additional employee and that method we are calling on button click. Every time when you click on that button angular will create new <tr> elements in place of old because by default angular keep track there object by an object reference and when you click on the button we are creating object reference of employee object that’s angular doesn’t know angular dealing with the same list of an element or different.

Now with trackBy, we can eliminate the creation of <tr> tags every time by tracking the id of the table as well as we can work with indexes also knowing even, odd, first and the last element achieve with this check out the example given below for that,

employee-detail.component.ts

import { Component, OnInit } from ‘@angular/core’;@Component({selector: ‘app-employee-details’,templateUrl: ‘./employee-details.component.html’,styleUrls: [‘./employee-details.component.css’]})export class EmployeeDetailsComponent implements OnInit {employees:any[];constructor() {this.employees=[{empid:’1',name:’Vaibhav’},{empid:’2',name:’Employee1'},{empid:’3',name:’Employee2'}];}ngOnInit() {}getEmployee():void{this.employees=[{empid:’1',name:’Vaibhav’},{empid:’2',name:’Employee1'},{empid:’3',name:’Employee2'},{empid:’4',name:’Employee3'}];}trackByEmpId(index:number,employee:any):string{return employee.empid;}}

employee-detail.component.html

<table><thead><tr><th>Employee ID</th><th>Employee Name</th><th>Index</th><th>First</th><th>Last</th><th>Even</th><th>Odd</th></tr></thead><tbody><tr *ngFor=”let employee of employees;trackBy:trackByEmpId;let i=index;let isFirst=first;let isLast=last;let isEven=even;let isOdd=odd”><td>{{employee.empid}}</td><td>{{employee.name}}</td><td>{{i}}</td><td>{{isFirst}}</td><td>{{isLast}}</td><td>{{isEven}}</td><td>{{isOdd}}</td></tr></tbody></table><br/><button (click)=”getEmployee()”>Refresh List</button>

Thank You, See you in the next article !!

You can reach out to me here,

LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar

Email: vaibhavbhapkar.medium@gmail.com

--

--

Vaibhav Bhapkar

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *