CdkVirtualScrollViewport header is not fixed

845 Views Asked by At

In my angular application, I want to keep my table header at fixed position and display the scrollbar to the body part only.

I am using CdkVirtualScrollViewport library from angular to plot the table content. But it is not giving me appropriate results. It is showing the scrollbar from the header itself. Kindly help me to resolve this issue. Attaching details below.

Html page

<cdk-virtual-scroll-viewport [itemSize]="25" [style.height.vh]="height" class="viewport">
    <table mat-table [dataSource]="dataSource" matSort aria-label="Elements" cdkDropListGroup class="table">

      <tr mat-header-row *matHeaderRowDef="columnsDef; sticky: true" class="column-header"></tr>
      <tr
        [style.backgroundColor]="hasTelematic(row) ? '#f3f3f3' : '#ffffff'"
        mat-row
        class="row-content"
        *matRowDef="let row; columns: columnsDef"
      ></tr>
    </table>
  </cdk-virtual-scroll-viewport>

Current result

enter image description here enter image description here

Expected result - Header should be at fixed postion.

enter image description here

Note: I tried solution provided in other forum but it is not working.

1

There are 1 best solutions below

1
On

I found one work around for it.

I have placed 2 cdk-virtual-scroll-viewreport. one for header and other for body. For header I have kept overflow-y as hidden so scroll bar wont be appearing for it.

Header

<cdk-virtual-scroll-viewport [itemSize]="25" [style.height.vh]="12" class="viewport" style="overflow-y: hidden;">
    <table mat-table [dataSource]="dataSource" matSort aria-label="Elements" cdkDropListGroup class="table">
      <tr mat-header-row *matHeaderRowDef="columnsDef; sticky: true" class="column-header"></tr>
    </table>
  </cdk-virtual-scroll-viewport>  

Body

<cdk-virtual-scroll-viewport [itemSize]="25" [style.height.vh]="height" class="viewport">
    <table mat-table [dataSource]="dataSource" matSort aria-label="Elements" cdkDropListGroup class="table">
      
      <tr
        [style.backgroundColor]="hasTelematic(row) ? '#f7f7f7' : '#ffffff'"
        mat-row
        class="row-content"
        *matRowDef="let row; columns: columnsDef"
      ></tr>
    </table>
  </cdk-virtual-scroll-viewport>