Scroll flickering issue - using cdk-virtual-scroll with scroll-snap-type

1.5k Views Asked by At

I am using cdk-virtual-scroll.

It is working fine without using the css property scroll-snap-type .

When I use scroll-snap-type it is flickering few seconds. herewith I attached the code sample https://stackblitz.com/edit/angular-gchlgl?file=src%2Fstyles.scss,src%2Fapp%2Fcdk-virtual-scroll-data-source-example.css,src%2Fapp%2Fcdk-virtual-scroll-data-source-example.html

Any help? Thanks.

1

There are 1 best solutions below

0
On

If you are using cdk-virtual-scroll, you should define the exact pixel size of your container and item. Because itemSize attribute is defining the size of the item. So in your code, the size of the items are same but in responsive size (not fixed using pixel), but you define the itemSize is 740px. I thought that will be crash the cdk-virtual-scroll to improve performance of your website while doing the calculation of rendering a lot of items.

I've update your code and add attributes itemSize, minBufferPx, maxBufferPx:

SEE DEMO: StackBlitz

HTML
<cdk-virtual-scroll-viewport
  itemSize="500"
  class="example-viewport"
  minBufferPx="1000"
  maxBufferPx="5000"
>
  <div *cdkVirtualFor="let item of ds" class="example-item">
    <div class="info">{{item}}</div>
    <img
      src="https://images.pexels.com/photos/7913028/pexels-photo-7913028.jpeg?auto=compress&cs=tinysrgb&w=1600&lazy=load"
      alt="Girl in a jacket"
    />
  </div>
</cdk-virtual-scroll-viewport>

And update some responsive CSS properties to fixed size:

CSS
.example-viewport {
  overflow-y: scroll;
  scroll-snap-type: y mandatory;
  width: 100%;
  height: 500px; /* updated from 100vh */
}

.example-item {
  height: 500px; /* updated from 100vh */
  scroll-snap-align: start;
  margin: 0 !important;
  padding: 0 10px !important;
  position: relative;
}

.info {
  position: absolute;
  top: 10px;
  left: 10px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  background-color: #0000008a;
  height: 25px;
  border-radius: 50px;
  padding: 0 10px;
  width: -webkit-fit-content;
  width: -moz-fit-content;
  width: fit-content;
  margin: 0 0 0 12px;
}

img {
  height: 500px; /* updated from 100vh */
  -o-object-fit: cover;
  object-fit: cover;
  -o-object-position: center center;
  object-position: center center;
}