3

In my Angular app, I'm using the Virtual Scroll from the Angular cdk.

This is my Component's template:

<cdk-virtual-scroll-viewport itemSize="50" class="example-viewport">
  <div *cdkVirtualFor="let item of items" class="example-item">{{item}}</div>
</cdk-virtual-scroll-viewport>

In my Component's class, I have a method that changes the array items giving to it new contents. The size of the array can change every time this method is called:

reload(newItems) {
  this.items = newItems;
}

After calling the method reload, the array of items is correctly updated and the view reflects this change. However, the scroll doesn't go back on top.

I would like to have the virtual scrolling to reset the scroll on top every time the items array is changed.

Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252

1 Answers1

12

I solved this issue by injecting a CdkVirtualScrollViewport inside my Component:

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

// ...
export class MyComponent {
  @ViewChild(CdkVirtualScrollViewport) virtualScroll: CdkVirtualScrollViewport;

  // ...

  reload(newItems) {
    this.items = newItems;
    this.virtualScroll.scrollToIndex(0);
  }
}

Calling this.virtualScroll.scrollToIndex(0); did the trick.

Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252
  • So if we are using multiple cdkvirtualscroll means how can we reset the scrollToIndex(0) Refer the Ex: https://stackblitz.com/edit/angular-7vcohv?file=src%2Fapp%2Fapp.component.html – Vignesh Jan 10 '20 at 13:49