typescript - Angular 7 - 虚拟滚动结合异步订阅
我在我的 Angular 7 项目中使用 async 来自动订阅我想要显示的数据。数据以大约 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}。
我想因为性能原因尝试这个功能。
答案#1
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
