【问题标题】:Performance issue with @angular/material autocomplete@angular/material 自动完成的性能问题
【发布时间】:2019-10-14 16:10:05
【问题描述】:

我正在使用 Angular/Material 自动完成功能。在将数据加载到自动完成时遇到严重的性能问题,例如渲染大约需要 30 秒,并且需要 10 多秒才能稳定,数据是从服务器加载的,从服务器接收的数据非常快。为了克服这个问题,我使用了 cdkVirtualScroll,在向下滚动到结束并再次单击文本框后,它在滚动其加载值后加载空弹出窗口。

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

查看前任:https://stackblitz.com/edit/angular-7vcohv?file=src%2Fapp%2Fapp.component.html

【问题讨论】:

    标签: angular8 typescript3.0 angular-material-8


    【解决方案1】:

    我认为核心问题是您使用 viewChild 来引用视口,但有多个视口。 html 中的自动完成设置与设置有类似的问题。

    下面的 StackBlitz 似乎正在运行。我认为如果您在屏幕上只有一个自动完成,那么您拥有它的方式会起作用。

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

    【讨论】:

      【解决方案2】:

      我不确定mat-autocomplete 支持多少选项,但我对提高性能的建议是:

      1. 只有在用户输入至少 2 个字符后才填写自动完成。
      2. 实现服务器端搜索并在您获得较少数量的选项后填充自动完成选项。
      3. 如果您认为这是 mat-autocomplete 组件的问题,您可以在 @angular/material repository 中提出问题。

      【讨论】:

      • 默认情况下我需要加载所有选项。基于 NgModel 值,我需要绑定这些值。
      • 抱歉,解决第 1 点的最佳 rxjs 运算符或最佳方法(仅在用户输入至少 2 个字符后才填写自动完成)?谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 2021-01-14
      • 2016-10-11
      • 2015-08-22
      • 2020-01-11
      • 2018-11-27
      相关资源
      最近更新 更多