DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators
  • How to Fix the OWASP Top 10 Vulnerability in Angular 18.1.1v
  • Implementing Micro Frontends in Angular: Step-By-Step Guide
  • AI: Do You Trust It?

Trending

  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • A Guide to Developing Large Language Models Part 1: Pretraining
  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  • How to Convert XLS to XLSX in Java
  1. DZone
  2. Data Engineering
  3. Data
  4. How To Use TrackBy With *ngFor in Angular 8

How To Use TrackBy With *ngFor in Angular 8

By 
Siddharth Gajbhiye user avatar
Siddharth Gajbhiye
·
Apr. 20, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
24.8K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

In this article, we are going to learn how to use TrackBy in Angular applications.

In every application, to run the application faster, we need to check the performance of our application. Angular provides a method called trackBy, which is used to track our incoming data every time we get a request from an API. 

Suppose we have some data coming from an API request into the collection, and we need to change the data over the web page using the ngFor directive. In this case, Angular will remove all the DOM elements that are associated with the data and will create them again in the DOM tree. That means a lot of DOM manipulations will happen if a large amount of data is coming from the API. 

Prerequisites

  • Basic knowledge of Angular.
  • Visual Studio Code must be installed.
  • Angular CLI must be installed.
  • Node JS must be installed.

Step 1

Let's create a new Angular project using the following NPM command:

TypeScript
 




xxxxxxxxxx
1


 
1
ng new trackBy  



Step 2

 Now, let's create a new component by using the following command:

TypeScript
 




xxxxxxxxxx
1


 
1
ng g c trackBy-example  



Step 3

 Now, open the trackBy-example.component.html file and add the following code in the file:

HTML
 




xxxxxxxxxx
1
34


 
1
<h4 style="text-align: center;">{{SampleMessage}}</h4>    
2
<div class="row">    
3
  <div class="col-12 col-md-12">    
4
    <div class="card">    
5
      <div class="card-body position-relative">    
6
        <div class="table-responsive cnstr-record product-tbl">    
7
          <table class="table table-bordered heading-hvr">    
8
            <thead>    
9
              <tr>    
10
                <th width="50">Art.No </th>    
11
                <th>Brand</th>    
12
                <th>Price/Unit</th>    
13
                <th>Provider</th>    
14
                <th>P. Art. N</th>    
15
                <th>S. A/C</th>    
16
              </tr>    
17
            </thead>    
18
            <tbody>    
19
              <tr *ngFor="let product of companyProduct;">    
20
                <td align="center">{{product.ArtNo}}</td>    
21
                <td>{{product.Brand}}</td>    
22
                <td>{{product.Price }}</td>    
23
                <td>{{product.Provider}}</td>    
24
                <td>{{product.ProviderArtNo}}</td>    
25
                <td>{{product.SalesAccount}}</td>    
26
              </tr>    
27
            </tbody>    
28
          </table>    
29
          <button (click)='getNewCompanies()'>New Companies</button>    
30
        </div>    
31
      </div>    
32
    </div>    
33
  </div>    
34
</div>   


 

Here, we are not using the trackBy function yet. 

In the below code, we can check how to apply trackBy with our structural directive, *ngFor:

HTML
 




xxxxxxxxxx
1


 
1
<tr *ngFor="let product of companyProduct; trackBy:trackByArtNo">  



Step 4

Now, open the trackBy-example.component.ts file and add the following code in this file:

TypeScript
 




xxxxxxxxxx
1
26


 
1
import { Component, OnInit } from '@angular/core';  
2
import { ProductsService } from '../product.service';  
3
  
4
@Component({  
5
  selector: 'app-trackby',  
6
  templateUrl: './trackby.component.html'  
7
})  
8
export class TrackbyComponent implements OnInit {  
9
  companyProduct: any[];  
10
  SampleMessage="Example of Angular Fetching records using TrackBy";  
11
  
12
  constructor(private productService: ProductsService) {  
13
  
14
  }  
15
  ngOnInit() {  
16
    this.companyProduct = this.productService.getAllProductsUsingTrackBy();  
17
  }  
18
  
19
  getNewCompanies(): void {  
20
    this.companyProduct = this.productService.getAllProductsUsingTrackByExample();  
21
  }  
22
  trackByArtNo(index: number, companyProduct: any): string {  
23
    return companyProduct.ArtNo;  
24
  }  
25
  
26
}  



The trackBy function will take two arguments. The first is the index, and the second is the current item. We can return the unique identifier as a return argument.

TypeScript
 




xxxxxxxxxx
1


 
1
trackByArtNo(index: number, companyProduct: any): string {    
2
   return companyProduct.ArtNo;    
3
 }  


  

Step 5

Now, open the product.service.ts file and add the following code:

TypeScript
 




x
111


 
1
import { Injectable } from '@angular/core';  
2
  
3
@Injectable()  
4
  
5
export class ProductsService {  
6
  employees: any[]; 
7
  
8
  constructor() {  
9
  }  
10
  
11
  getAllProductsUsingTrackBy() {  
12
    return this.employees = [  
13
      {  
14
        ProductId: 1,  
15
        ArtNo: "100",  
16
        Provider: "OppoProvider",  
17
        ProviderArtNo: "1Yu",  
18
        Brand: "Oppo",  
19
        Price: 7810.23,  
20
        BuyAccount: "123",  
21
        SalesAccount: "321"  
22
      },  
23
      {  
24
        ProductId: 1,  
25
        ArtNo: "101",  
26
        Provider: "OppoProvider",  
27
        ProviderArtNo: "1Yu",  
28
        Brand: "Oppo",  
29
        Price: 2310.23,  
30
        BuyAccount: "123",  
31
        SalesAccount: "321"  
32
      },  
33
      {  
34
        ProductId: 1,  
35
        ArtNo: "102",  
36
        Provider: "OppoProvider",  
37
        ProviderArtNo: "1Yu",  
38
        Brand: "Oppo",  
39
        Price: 7810.23,  
40
        BuyAccount: "123",  
41
        SalesAccount: "321"  
42
      },  
43
      {  
44
        ProductId: 1,  
45
        ArtNo: "103",  
46
        Provider: "OppoProvider",  
47
        ProviderArtNo: "1Yu",  
48
        Brand: "Oppo",  
49
        Price: 5810.23,  
50
        BuyAccount: "123",  
51
        SalesAccount: "321"  
52
      }  
53
    ];  
54
  }  
55
  
56
  getAllProductsUsingTrackByExample() {  
57
    return this.employees = [  
58
      {  
59
        ProductId: 1,  
60
        ArtNo: "100",  
61
        Provider: "OppoProvider",  
62
        ProviderArtNo: "1Yu",  
63
        Brand: "Oppo",  
64
        Price: 7810.23,  
65
        BuyAccount: "123",  
66
        SalesAccount: "321"  
67
      },  
68
      {  
69
        ProductId: 1,  
70
        ArtNo: "101",  
71
        Provider: "OppoProvider",  
72
        ProviderArtNo: "1Yu",  
73
        Brand: "Oppo",  
74
        Price: 2310.23,  
75
        BuyAccount: "123",  
76
        SalesAccount: "321"  
77
      },  
78
      {  
79
        ProductId: 1,  
80
        ArtNo: "102",  
81
        Provider: "OppoProvider",  
82
        ProviderArtNo: "1Yu",  
83
        Brand: "Oppo",  
84
        Price: 7810.23,  
85
        BuyAccount: "123",  
86
        SalesAccount: "321"  
87
      },  
88
      {  
89
        ProductId: 1,  
90
        ArtNo: "103",  
91
        Provider: "OppoProvider",  
92
        ProviderArtNo: "1Yu",  
93
        Brand: "Oppo",  
94
        Price: 5810.23,  
95
        BuyAccount: "123",  
96
        SalesAccount: "321"  
97
      },  
98
      {  
99
        ProductId: 1,  
100
        ArtNo: "104",  
101
        Provider: "OppoProvider",  
102
        ProviderArtNo: "1Yu",  
103
        Brand: "Oppo",  
104
        Price: 4770.23,  
105
        BuyAccount: "143",  
106
        SalesAccount: "211"  
107
      },  
108
    ];  
109
  }  
110
  
111
}  



Now, it's time to run the project by using npm start or ng serve command and check the output. As in the below image, when we click on "New Companies" it will add one new entry in the table. 

Adding new companies
Adding new companies

If we use the normal *ngFor directive without using the trackBy function, the Angular application will remove all the DOM elements and will recreate them again in the DOM tree, even if the same data is coming. This can slow down our application performance if there's a lot of data. 

Application performance
Application performance


But, with the help of trackBy, it will not create a new DOM, as we can see in the below image. Only the new data in the DOM will be added, which will increase the application performance.
 

Only new data added to the DOM

Only new data added to the DOM

Conclusion

In this article, we have seen how to use trackBy with NgFor in an Angular 8 Application.

Please give your valuable feedback/comments/questions about this article. Please let me know if you liked and understood this article, and how I could improve it.

AngularJS application Data (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators
  • How to Fix the OWASP Top 10 Vulnerability in Angular 18.1.1v
  • Implementing Micro Frontends in Angular: Step-By-Step Guide
  • AI: Do You Trust It?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!