Improve the Performance of Angular Material Select and Autocomplete to Handle 100k+ Data
Problem statement
You have to create a select dropdown and autocomplete which can handle 100k+ data seamlessly while capturing the same look and feel of material UI.
Angular material select and autocomplete works fine when you have less data but as soon as data increases the render time will increase, scroll will become erratic which will make it pretty much unusable.
Solution
So, how do we deal with this problem? Thankfully Angular have cdk-virtual-scroll
. This helps up in displaying large lists of elements performantly by only rendering the items that fit on-screen. Loading hundreds of elements can be slow in any browser; virtual scrolling enables a performant way to simulate all items being rendered by making the height of the container element the same as the height of total number of elements to be rendered, and then only rendering the items in view.
Let’s see how we can use it inside mat-select
and mat-autocomplete
.
<!-- Select Dropdown -->
<!-- itemSize is configurable. And it must have a fixed height --><mat-form-field>
<mat-select placeholder="Large dataset example">
<cdk-virtual-scroll-viewport
itemSize="25"
[ngStyle]="{height: '200px'}">
<mat-option
*cdkVirtualFor="let entry of entries"
[value]="entry">…