Angular 7 - 虚拟滚动与异步订阅相结合

Angular 7 - virtual scroll combined with async subscription

我在我的 Angular 7 项目中使用 async 来自动订阅我想要显示的数据。数据显示为 table,大约有 2000 项。

以下代码来自我的模板:

<table class="table table-responsive">
  <tr *ngFor="let s of data | async | searchFilter: {keyName: searchText}">
    <td>Display some data: {{s.someProperty}}</td>
  </tr>
</table>

我不清楚如何使用 Angular 7 的这个新功能来仅渲染可见数据,同时仍然使用我的管道 async | searchFilter: {keyName: searchText}

由于性能原因,我想试用此功能。

Angular Material 团队在 https://material.angular.io 开发了一些很好的文档来帮助您成功应用他们包的任何功能。特别是,您的代码可以轻松更改为使用虚拟滚动。

在您的模块中(app.module.ts 或针对您的特定功能的模块):

import { ScrollingModule } from '@angular/cdk/scrolling';

@NgModule({
  imports: [
    // other imports,
    ScrollingModule,
  ],
  // other normal module declaration stuff
})
export class AppModule { }

然后,在你的 component.html:

<cdk-virtual-scroll-viewport [itemSize]='32'> <!-- or whatever the size of each item is -->
  <table class="table table-responsive">
    <tr *cdkVirtualFor="let s of data | async | searchFilter: {keyName: searchText}">
      <td>Display some data: {{s.someProperty}}</td>
    </tr>
  </table>
</cdk-virtual-scroll-viewport>

注意事项:

  • 而不是 table 行的 *ngFor 指令,你应该是 使用 *cdkVirtualFor 指令
  • 您必须将整个 table 包裹在 一组标签并指定高度 itemSize(不要忘记 itemSize 两边的括号)
  • 除了如上所述使用 *cdkVirtualFor 指令外,您不必更改访问数据的方式;它旨在以与 *ngFor
  • 完全相同的方式使用

有关在 table 和列表中使用虚拟滚动的更多信息,请参见此处:https://material.angular.io/cdk/scrolling/overview#elements-with-parent-tag-requirements