How to set the initial index (position) for the CdkVirtualScrollViewport in Angular 7
Asked Answered
B

3

7

I need the inital position of the cdk-virtual-scroll-viewport to be other than the first element / item of the list.

Now I found the scrollToIndex and scrollTo methods, but I only can get them to work when using it in the ngAfterViewChecked, which feels off.

  1. Can someone confirm that the using those methods in the ngAfterViewChecked is the right way of doing things?
  2. If not, show an alternative method / technique?

  @ViewChild(CdkVirtualScrollViewport) cdkVirtualScrollViewport: CdkVirtualScrollViewport;
  numbers: number[] = [];

  constructor() {
    for (let index = 0; index < 10000; index++) {
      this.numbers.push(index);
    }
  }

  ngAfterViewChecked() {
    this.cdkVirtualScrollViewport.scrollToIndex(2000);
  }
  <ul class="list">
    <cdk-virtual-scroll-viewport style="height:264px" itemSize="88">
      <ng-container *cdkVirtualFor="let n of numbers">
        <li style="height:88px">{{ n }}</li>
      </ng-container>
    </cdk-virtual-scroll-viewport>
  </ul>
Bydgoszcz answered 12/11, 2018 at 19:52 Comment(1)
Have you found the solution? If so, please provide the answer. Thanks.Colchicine
O
1

I have the same problem, I have a not so elegant solution

contentCheck = 0

ngAfterViewChecked() {
  if (this.contentCheck < 3) {
  this. cdkVirtualScrollViewport.scrollToIndex(4000);
  this.contentCheck++;
 }
}

After 3 checks the scrollToIndex works.

Obi answered 12/12, 2018 at 3:18 Comment(0)
C
0

Although not a perfect solution, you can achieve this behavior by combining afterViewInit with setTimeout:

ngAfterViewInit() {
    setTimeout(() => {
        this.cdkVirtualScrollViewport.scrollToIndex(50);
    });
}
Crosswalk answered 4/7, 2019 at 15:21 Comment(0)
R
0

We can use the setRenderedRange method:

@ViewChild(CdkVirtualScrollViewport) virtualScroll: CdkVirtualScrollViewport;

ngAfterViewInit() {
    const offset = 10; // that's an example
    if (this.virtualScroll) {
        setTimeout(() => {
            const currentRange = this.virtualScroll.getRenderedRange();
            this.virtualScroll.setRenderedRange({ start: currentRange.start + offset, end: currentRange.end + offset });
        });
    }
}

Note: I am not sure if it is specific to my use case, but by just setting the expected range, the previous items do not seem to be considered (we cannot scroll up). It seems important to use scrollToIndex so the scroll is properly updated. Here is my workaround, setting the range minus one, then scrolling by one more:

    const currentRange = this.virtualScroll.getRenderedRange();
    this.virtualScroll.setRenderedRange({ start: currentRange.start + offset - 1, end: currentRange.end + offset - 1});
    this. virtualScroll.scrollToIndex(offset);
Recept answered 17/12, 2020 at 15:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.