DEV Community

Cover image for How I fixed a performance issue in a dropdown that rendered 4000 options .
mansi shrivastava
mansi shrivastava

Posted on

How I fixed a performance issue in a dropdown that rendered 4000 options .

So, I have this goal to render lots of options in my Angular application. Obviously, the data is coming from the API, and I was using a simple forEach loop to display that. But the issue is performance. Is it ideal to use forEach for rendering options? I guess not, right? So, I figured out some options for you.

1. Virtual scrolling

<cdk-virtual-scroll-viewport appendOnly itemSize="50" class="example-viewport">
  <div *cdkVirtualFor="let item of items" class="example-item">{{item}}</div>
</cdk-virtual-scroll-viewport
Enter fullscreen mode Exit fullscreen mode

Reference — https://material.angular.io/cdk/scrolling/overview

Setup

  • Install npm install @angular/cdk
  • Add CDK to Your Project ng add @angular/cdk
  • Import the following module
import { ScrollingModule } from '@angular/cdk/scrolling';
Enter fullscreen mode Exit fullscreen mode

Use in your HTML
Image description

<cdk-virtual-scroll-viewport itemSize="70" class="viewport">
  <div *cdkVirtualFor="let option of options" class="item">
    {{ option }}
  </div>
</cdk-virtual-scroll-viewport>
Enter fullscreen mode Exit fullscreen mode

2. Lazy Load Scroll

<div *ngFor="let option of options" (scroll)="onScrollDropdown()">
  {{ option }}
</div>

onScrollDropdown() {
  if (this.isNearBottom()) {
    this.loadMoreOptions();
  }
}
Enter fullscreen mode Exit fullscreen mode

The purpose of Lazy Load Scroll is to load more items as the user scrolls down the list, improving performance by fetching data only when it’s needed

3. Track By

<div *ngFor="let user of users; trackBy:userByName">
{{user.name}} -> {{user.score}}
</div>

public function userByName(index: number, user: User): id {
  return user?.id;
}
Enter fullscreen mode Exit fullscreen mode

The purpose of using trackBy is to assign a unique identity to each element in a list. If Angular finds two elements with the same identity, it only updates the content if it has changed. Without trackBy, Angular relies on object references, which often change even if the content stays the same. This can cause Angular to unnecessarily re-render the entire list.

Thanks for reading 👍

Visit my website

As I continue to enhance this post with additional frameworks, I will make further edits to improve it. Hopefully, these updates will provide more clarity and value.
https://mansishrivastava12.medium.com/how-i-fixed-a-performance-issue-in-a-dropdown-that-rendered-4000-options-914ae86e9cbc

Top comments (0)