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

Mansi Shrivastava
2 min read1 day ago

--

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

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';
  • Use in your HTML
<cdk-virtual-scroll-viewport itemSize="70" class="viewport">
<div *cdkVirtualFor="let option of options" class="item">
{{ option }}
</div>
</cdk-virtual-scroll-viewport>

2. Lazy Load Scroll

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

onScrollDropdown() {
if (this.isNearBottom()) {
this.loadMoreOptions();
}
}

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;
}

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 👍

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://github.com/Mansishrivastava

--

--

Mansi Shrivastava
Mansi Shrivastava

Written by Mansi Shrivastava

I specialise in building user-friendly and visually appealing websites and applications.

No responses yet