Angular 7 - virtual scroll combined with async subscription

4.5k views Asked by At

I am using async in my Angular 7 project to automatically subscribe my data I want to display. The data is displayed as a table with about 2000 items.

The following code is from my template:

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

It is not clear to me how to use this new feature of Angular 7 for only rendering viewable data with still using my pipes async | searchFilter: {keyName: searchText}.

I want to try out this feature because of performance reasons.

1

There are 1 answers

0
night_owl On BEST ANSWER

The Angular Material team has developed some good documentation at https://material.angular.io to help you apply any of the features of their package successfully. In particular, your code can easily be changed to use virtual scrolling.

In your module (either app.module.ts or the module for your specific feature):

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

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

Then, in your 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>

Things to note:

  • Instead of the *ngFor directive for the table rows, you should be using the *cdkVirtualFor directive
  • You must wrap the entire table in a set of tags and specify the height in itemSize (don't forget the brackets around itemSize)
  • You don't have to change the way you access your data, other than using the *cdkVirtualFor directive as mentioned above; it is designed to be used in exactly the same way as *ngFor

More information on using virtual scrolling with tables and lists can be found here: https://material.angular.io/cdk/scrolling/overview#elements-with-parent-tag-requirements