0

I would like to scroll programmatically to the end of a the cdk-virtual-scroll-viewports after adding new elements.

I am trying to use the method:

this.viewport.scrollToIndex(...);

but it does not seem to work as expected: https://stackblitz.com/edit/angular7-virtual-scroll-oqrbjv

What am I doing wrong? I don't really want a virtual scrolling anyways, so do I need the cdk-virtual-scroll-viewport or is there an alternative?

M4V3N
  • 600
  • 6
  • 21
  • Possible duplicate of [How to programmatically scroll to item with angular's material virtual scroll?](https://stackoverflow.com/questions/54551205/how-to-programmatically-scroll-to-item-with-angulars-material-virtual-scroll) – Jota.Toledo May 05 '19 at 11:52
  • Your code is wrong: the size of your items in css is 50px, but you are binding 1 to the `itemSize` of the `cdk-virtual-scroll-viewport` element – Jota.Toledo May 05 '19 at 11:53

2 Answers2

1

Try this with 2 buttons. The one will add Data and the other will scroll to the end.

https://stackblitz.com/edit/angular7-virtual-scroll-y3u2pw

So the 1st button will be like this:

<button type="button" (click)="addData()">Add Data</button>

The add function will be like this:

addData(){
   for(let i = 0; i < 10; i++) {
   this.data.push(i);
 }
}

And the 2nd button will be like this:

<button type="button" (click)="gotoLastIndex()">Go to last Index</button>

The function will be like this:

gotoLastIndex() {
  this.viewport.scrollToIndex(this.data.length);
}

And for itemSize you will need to set it to 50 equal with the height of class="example-item" so you will have : <cdk-virtual-scroll-viewport itemSize="50" class="example-viewport">

tufonas
  • 303
  • 1
  • 7
1

You can use setTimeout to tell Angular that your data has changed

https://stackblitz.com/edit/angular7-virtual-scroll-135zu5?file=app/cdk-virtual-scroll-data-source-example.ts

  gotoLastIndex() {
    for (let i = 0; i < 10; i++) {
      this.data.push(i);
    }

    // execute after angular's data binding
    setTimeout(() => {
      this.viewport.scrollToIndex(99999);
    })
  }
Chunbin Li
  • 2,196
  • 1
  • 17
  • 31