Saturday, 21 September 2024

Trackby in ngFor Angular

  Angular Trackby option improves the Performance of the ngFor if the collection has a large no of items and keeps changing. This can significantly reduce the number of DOM manipulations required, especially in large lists.

Here's a brief overview of how to use trackBy:

Syntax

You can use trackBy by providing a function that returns a unique identifier for each item in the list. This function is typically defined in your component class.

Example

Suppose you have a list of items that you want to display:

// In your component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-item-list',
  template: `
    <ul>
      <li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
    </ul>
  `
})
export class ItemListComponent {
  items = [
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' },
    { id: 3, name: 'Item 3' }
  ];

  trackById(index: number, item: any): number {
    return item.id; // Return unique identifier
  }
}

How It Works

  1. Define a Unique Identifier: The trackById function returns the unique id of each item. This helps Angular track which items have changed.

  2. Use trackBy in *ngFor: Add trackBy: trackById to the *ngFor directive.

Benefits

  • Performance: By using trackBy, Angular can skip re-rendering items that haven’t changed, which improves performance, especially with large datasets.
  • Reduced Reconciliation: It minimizes the work done during change detection by only updating the items that have changed.

When to Use trackBy

You should consider using trackBy whenever you're rendering lists, particularly when:

  • The list is large.
  • The items in the list may change frequently.
  • You want to improve the performance of your application.

Using trackBy is a best practice in Angular for rendering lists efficiently.



0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives