angulartypescriptscrollangular7virtualscroll

Angular 7 - virtual scroll combined with async subscription


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.


Solution

  • 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:

    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