CodexBloom - Programming Q&A Platform

Angular 15: How to Handle Long List Rendering with Virtual Scrolling and TrackBy?

👀 Views: 98 💬 Answers: 1 📅 Created: 2025-06-21
angular virtual-scrolling performance typescript

I'm having a hard time understanding I'm reviewing some code and I'm relatively new to this, so bear with me. I'm working on an Angular 15 application that displays a long list of items fetched from an API, and I'm trying to optimize rendering using virtual scrolling with `*cdkVirtualFor`. However, I'm running into performance issues and unnecessary re-renders. I have the following setup: ```typescript import { Component, OnInit } from '@angular/core'; import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling'; import { ItemService } from './item.service'; @Component({ selector: 'app-item-list', template: ` <cdk-virtual-scroll-viewport itemSize="50" class="example-viewport"> <div *cdkVirtualFor="let item of items; trackBy: trackById" class="example-item">{{item.name}}</div> </cdk-virtual-scroll-viewport> `, styles: [`.example-viewport { height: 400px; width: 100%; } .example-item { height: 50px; }`] }) export class ItemListComponent implements OnInit { items: any[] = []; constructor(private itemService: ItemService) {} ngOnInit() { this.itemService.getItems().subscribe(data => { this.items = data; }); } trackById(index: number, item: any): number { return item.id; // assuming each item has a unique id } } ``` I have ensured to implement the `trackBy` function to minimize re-renders, but I still notice that every time new items are fetched or the list updates, the entire list seems to be re-rendered, causing noticeable lag in the UI. Could there be something I'm missing in my setup, or any additional configurations needed for `CdkVirtualScrollViewport` to efficiently handle large datasets? I've tried checking the Angular change detection strategy and even switched to `ChangeDetectionStrategy.OnPush`, but that didn’t resolve the issue. The API returns around 10,000 items, and while I have pagination implemented, the initial load is still sluggish. Any tips on improving the performance would be greatly appreciated! My development environment is Windows. My development environment is macOS. Thanks in advance! The stack includes Typescript and several other technologies. I'd really appreciate any guidance on this.