trackBy in ngFor 🎯Welcome to this comprehensive guide on Angular's trackBy function within the ngFor directive! In this lesson, we'll dive deep into understanding what trackBy is, why we need it, and how to effectively use it in our projects. Let's get started! 📝
trackBy? 💡trackBy is a custom function provided by Angular for the ngFor directive. This function helps Angular identify which items in a list have changed, been added, or removed, improving the performance of the application, especially when dealing with large data sets.
trackBy? 💡When using the ngFor directive without trackBy, Angular performs a diffing operation on the entire list every time the data source changes. This can lead to poor performance, especially with large data sets.
By providing a trackBy function, Angular can identify which items have changed and only update those, resulting in improved performance.
trackBy 💡To use trackBy, we need to pass a function to the trackBy input of the ngFor directive. This function takes two arguments: the old item and the new item. It should return a unique identifier for each item in the list.
Here's a simple example:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<ul>
<li *ngFor="let item of items; trackBy: trackByItem">
{{ item.id }} - {{ item.name }}
</li>
</ul>
`,
})
export class ExampleComponent {
items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
];
trackByItem(index: number, item: any) {
return item.id;
}
}In this example, we've defined a trackByItem function that returns the unique identifier (id) for each item in the items array.
trackBy Usage 💡In real-world projects, our data might not have a built-in unique identifier. In such cases, we can create a custom identifier. Here's an example:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<ul>
<li *ngFor="let item of items; trackBy: trackByItem">
{{ item.name }}
</li>
</ul>
`,
})
export class ExampleComponent {
items = [
{ name: 'Item 1' },
{ name: 'Item 2' },
{ name: 'Item 3' },
];
trackByItem(index: number, item: any) {
return item ? item.constructor.name + index : undefined;
}
}In this example, we've defined a trackByItem function that returns a combination of the object's constructor name and the index. This ensures a unique identifier for each item, even if they don't have a built-in unique identifier.
What does the `trackBy` function do in Angular's `ngFor` directive?
That's it for this lesson on Angular's trackBy function within the ngFor directive! Understanding and using trackBy can significantly improve the performance of your Angular applications, especially when dealing with large data sets.
Stay tuned for more lessons on Angular and happy coding! 💡💻🎉