Skip to main content

Angular NgFor directive and trackby

angular ngfor trackby example


Today we will learn about NgFor one of the core directive of angular. NgFor helps to build list and tables in Angular

 

Let us see the example in our flower store app. In the landing page I am going to print list of flowers that are available in the store. Later we will add images and show them in a carousel to rotate automatically.


First we will create the domain class called flower.ts and you can copy paste below code. 


export class flower{
  constructor() { }
  name:string='';
  price:number = 0;
  availableQuantity:number = 0
}


To use this domain class inside another component you must specify export keyword along with the class keyword.

Flower domain has 3 attributes to store name of the flower then price and the available quantity.

Now we can create the array from the flower type as below inside the landing.component.ts file.


myFlowerList:flower[]=[];


I will call a method inside ngOnInit to add values to the array as below.

ngOnInit is one of the life cycle hooks used in angular and it executed only one time when component is initiating.


ngOnInit() {
    this.mySellingFlowers();
  }

  mySellingFlowers(){
    let rose = new flower();
    rose.name = "Rose";
    rose.price = 100;
    rose.availableQuantity = 1000;
    this. myFlowerList.push(rose);

    let lily = new flower();
    lily.name = "Lily";
    lily.price = 80;
    lily.availableQuantity = 2000;
    this. myFlowerList.push(lily);

    let tulip = new flower();
    tulip.name = "Tulip";
    tulip.price = 100;
    tulip.availableQuantity = 2300;
    this. myFlowerList.push(tulip);

    let carnation = new flower();
    carnation.name = "Carnation";
    carnation.price = 50;
    carnation.availableQuantity = 1500;
    this. myFlowerList.push(carnation);
  }


Now we have an array with different flowers. Let’s see how we can iterate the array using ngFor directive.

Copy paste below code in you landing.component.html file.


<ul>
    <li *ngFor="let flower of myFlowerList">
        {{flower.name}}
    </li>
</ul>
 


myFlowerList is the array that we defined and initiated in the landing.component.ts file.

*ngFor is helping to loop the array element and it will hold each element in flower object and you can access it properties with the . operator.

{{}} is called interpolation and it will print the value of the variable in your browser.

Now let’s check our browser. Here it is.


angular ngfor trackby example - flower store

Finding the index of a list element

 

Now let’s see how you can track the index of each element and use that index to generate unique id for each flower element.


<ul>

    <li *ngFor="let flower of myFlowerList;let i = index">

        <span id="flower_{{i}}">{{flower.name}}</span>

    </li>

</ul>
track the index of each element and use that index to generate unique id

How to use trackBy?

Track by function is using to improve performance. If you don’t use track by function whenever your array get change it will reload the whole DOM object but with track by function it will change only that element.

 

To use trackby function you can update landing.component.html file as below


<ul>
    <li *ngFor="let flower of  myFlowerList;trackBy:trackFlowers">
        <span >{{flower.name}}</span>
    </li>
</ul>


Then define the trackFlower function in landing.component.ts file as below.


trackFlowers(index,flower){
    return flower?flower.name:undefined
}

I hope you enjoyed the post. In next post we will apply some styles and background flower images to our flower list.


Comments

Popular posts from this blog

Building robust APIs with Node.js

Node.js is a popular open-source JavaScript runtime environment that allows developers to build scalable and high-performance web applications. One of the key strengths of Node.js is its ability to build APIs quickly and efficiently. APIs, or Application Programming Interfaces, allow different systems to communicate with each other, enabling data exchange and other operations. Building robust APIs with Node.js requires an understanding of RESTful architecture, which is a widely adopted standard for creating APIs. RESTful APIs provide a standardized way to expose data and functionality over the web using a set of HTTP methods such as GET, POST, PUT, and DELETE. To build a robust Node.js API, developers must choose an appropriate framework and set up a development environment. They should also handle errors and exceptions, implement authentication and authorization, and use middleware to enhance the functionality of the API. Writing test cases, documenting the API using tools such as Swa...

PrimeNG UI Components For Angular Application

Getting Started With PrimeNG Styling in Angular App  This chapter we are going to check how you can add PrimeNG card component to show available flowers in the stock. Before styling the app, I have added some images of flowers to our assets folder as below. In app.module.ts file you can import PrimeNG Card module as below. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LandingComponent } from './modules/landing/landing.component'; import { HomeComponent } from './modules/home/home.component'; import { CardModule } from 'primeng/card'; ; @NgModule({   declarations: [     AppComponent,     LandingComponent,     HomeComponent   ],   imports: [     BrowserModule,     AppRoutingModule,     CardModule,        ],   provider...

SMPP protocol library for fast and easy SMSC(Short Message Service Centre) client development even for non-telecom guys

SMS sending through .NET C# is really easy. But most of the guys face many issues with SMSC client developments. SMPP protocol has many parameters to configure, but for simple SMPP gateway application you need very few of them to configure correctly. This article will cover how to implement SMSC client application using EasySMPP library. EasySMPP is a free SMPP library used by many people to implement SMS sending applications. There are many SMPP libraries but EasySMPP library is very easy to use and relatively stable. EasySMPP library mainly contain five class library projects. KernelParameters, SMPPClient, SMSClient, SMSService and Tools are the library projects and you only need to use SMSClient library to implement SMPP client application. First download EasySMPP library and add class library project to your .NET C# solution.  1. public bool SendSms( string from, string to, string text)