[Fixed] Angular Virtual Scroll display issues

Issue

I have been trying to find a solution for a couple of days for this, but can’t seem to find one.

We have a lot of mat-cards loading and thought it best to add virtual-scrolling, however it immediately changed the display to rows (showing all the mat-cards stacked below one another). I have rewritten the section a couple of times to no avail.

<div fxLayout style="margin-top: 40px" class="row">
    <cdk-virtual-scroll-viewport [itemSize]="20" class="example-viewport">
      <div fxFlex.gt-md="265px" fxFlex.lg="265px" *cdkVirtualFor="let course of courses | courseDrop : typeView | courseTemp: courseSearch">
        <mat-card class="course-card" >
         ...content
        </mat-card>
      </div>
    </cdk-virtual-scroll-viewport>
  </div>

Solution

Yes, that is the limitation for virtual scroll – it works with rows.

If you need to have items displayed next to each other, you need to split those in the component into groups and have the virtual scroll work on groups.

Since you’re using breakpoints, you’d need to do some work on listening to breakpoint changes. You can do that by using the MediaObserver.

You would need to adjust the filtering or do it in the component. I’m leaving that out.

function split<T>(input: T[], groupSize: number): T[][]  {
  const out: T[][] = [];
  for(let i=0; i < input.length; i += groupSize) {
    out.push(input.slice(i, i + groupSize));
  }
  return out;
}


mediaObserver.media$.subscribe((change: MediaChange) => {
      
      if ( change.mqAlias == 'xs') {
         this.viewCourses = split(this.courses,1);
      }
      if ( change.mqAlias == 'md') {
         this.viewCourses = split(this.courses,2);
      }
      if ( change.mqAlias == 'lg') {
         this.viewCourses = split(this.courses,3);
      }
    });


<div fxLayout style="margin-top: 40px" class="row">
    <cdk-virtual-scroll-viewport [itemSize]="20" class="example-viewport">
      <div *cdkVirtualFor="let courses of viewCourses">
        <div fxFlex.gt-md="265px" fxFlex.lg="265px" *ngFor="let course of courses">
        <mat-card class="course-card" >
         ...content
        </mat-card>
        </div>
      </div>
    </cdk-virtual-scroll-viewport>
  </div>

Leave a Reply

(*) Required, Your email will not be published