首页 > 解决方案 > Angular 7 - 虚拟滚动与异步订阅相结合

问题描述

async在我的 Angular 7 项目中使用自动订阅我想要显示的数据。数据显示为包含大约 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}

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

标签: angulartypescriptscrollangular7virtualscroll

解决方案


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>

注意事项:

  • 您应该使用 *cdkVirtualFor 指令,而不是表行的 *ngFor 指令
  • 您必须将整个表格包装在一组标签中并在 itemSize 中指定高度(不要忘记 itemSize 周围的括号)
  • 除了使用上面提到的 *cdkVirtualFor 指令外,您不必更改访问数据的方式;它的使用方式与 *ngFor 完全相同

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


推荐阅读