Efficient List Rendering in Angular
When loading new data into an Angular template, selectively update only the modified list elements instead of re-rendering the entire HTML list. This approach prevents screen flicker and ensures a smoother, uninterrupted user experience.
Published: 6/29/2024When working with dynamic lists in Angular using *ngFor, the framework by default re-renders the entire list whenever
the underlying data changes, even if only a few items have been added, removed, or modified. This can lead to
performance issues, especially with large lists, and can cause a noticeable “flicker” or loss of focus/state for
interactive elements within the list.
To combat this, Angular provides the trackBy function. By supplying trackBy to your *ngFor directive, you instruct
Angular to uniquely identify each item in the list based on a specific property, rather than its position in the array.
This allows Angular to intelligently re-render only the elements that have actually changed, significantly improving
performance and user experience.
Set a unique identifier key that Angular will use under the hood for rendering:
<ng-container *ngFor="let post of posts; trackBy: trackByFn"> ...</ng-container>
The trackByFn function receives the index and the item itself. It should return a unique identifier for each
item.
Assuming that post.id is a string and serves as a unique identifier for each post:
trackByFn(index: number, post: Post): string {
return post.id;
}
Using trackBy ensures that Angular can efficiently manage the DOM, preserving the state of existing components or
elements in the list and only creating or destroying those that are genuinely new or removed. This is particularly
beneficial for animations, input fields, or any interactive elements within your *ngFor loops.