6

I am using Angular/Material Autocomplete. While loading data to the Autocomplete getting serious performance issues,like the rendering takes around 30 seconds and it takes more than 10 seconds to become stable,data is loaded from the server, and the data received from the server is quite fast. To Over Come that issue i used cdkVirtualScroll, after scrolling down to end and clicking again the text box it's loading empty popup after scroll its loading values.

html

   <mat-form-field>
      <input type="text" placeholder="Pick one" aria-label="Number" matInput [matAutocomplete]="auto">
      <mat-autocomplete #auto="matAutocomplete" (opened)="panelOpened()">
        <cdk-virtual-scroll-viewport itemSize="48" style="height: 240px" minBufferPx="96" maxBufferPx="144">
          <mat-option *cdkVirtualFor="let option of options" [value]="option">
            {{option}}
          </mat-option>
        </cdk-virtual-scroll-viewport>
        </mat-autocomplete>
    </mat-form-field>

TS

export class AppComponent  {
  options: string[] = [];

  @ViewChild(CdkVirtualScrollViewport, {static: true}) viewport: CdkVirtualScrollViewport;

  constructor() {
    for (let i = 0; i < 10000; i++) {
      this.options.push("#"+i);
    }
  }

  panelOpened() {
    if (this.viewport) {
      this.viewport.checkViewportSize();
    }
  }
}

Check the ex: https://stackblitz.com/edit/angular-7vcohv?file=src%2Fapp%2Fapp.component.html

Vignesh
  • 2,378
  • 3
  • 25
  • 48

2 Answers2

4

I'm not sure how many options the mat-autocomplete is targeted to support, but my suggestions to improve the performance are:

  1. Fill the autocomplete only after the user typed at least 2 characters.
  2. Implement a server-side search and fill the auto-complete options after you got smaller amount of options.
  3. If you think this is an issue with the mat-autocomplete component, you can open an issue in the @angular/material repository.
TheUnreal
  • 23,434
  • 46
  • 157
  • 277
  • 1
    By default i need to load all the options. Based on NgModel value i need to bind the values. – Vignesh May 29 '19 at 09:03
  • 1
    Sorry, which the best rxjs operator, or the best way, to solve the point 1 (Fill the autocomplete only after the user typed at least 2 characters)? Thanks – timhecker Oct 30 '20 at 16:48
0

I believe the core problem is that you are using viewChild to reference the viewPort but there are multiple viewports. The AutoComplete setup in the html had similar issues with the setup.

The below StackBlitz seems to be working. I would think the way you had it would work though if you only had one auto complete on the screen.

https://stackblitz.com/edit/angular-rzqjz8?file=src%2Fapp%2Fapp.component.ts

Kyle Anderson
  • 724
  • 3
  • 10