CodexBloom - Programming Q&A Platform

Angular 15: implementing Change Detection and TrackBy in ngFor with Large Lists

๐Ÿ‘€ Views: 0 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-13
angular ngfor performance changedetection typescript

I'm sure I'm missing something obvious here, but I'm testing a new approach and I've been struggling with this for a few days now and could really use some help. I'm working with important performance optimization when rendering a large list of items in Angular 15 using `ngFor`. I've implemented `trackBy` to optimize the change detection process, but I still notice frequent re-renders causing the UI to lag. Hereโ€™s a simplified version of my component: ```typescript 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 = Array.from({ length: 10000 }, (_, i) => ({ id: i, name: `Item ${i}` })); trackById(index: number, item: { id: number }) { return item.id; } } ``` Iโ€™ve also checked for unnecessary changes on the items by ensuring that their objects donโ€™t get mutated. However, whenever I add or remove items from the list, I observe that the entire list is being re-rendered instead of just the affected items. I even tried using `OnPush` change detection strategy on the component but didn't notice any improvements. Furthermore, I'm getting this behavior in the console intermittently: `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.` This seems to be related to updates happening outside Angular's zone. Is there a better approach to handle large lists with change detection in Angular? What am I missing here? My development environment is Ubuntu. How would you solve this? I'd love to hear your thoughts on this. For reference, this is a production REST API. What would be the recommended way to handle this?