Search code examples
angularangular-materialangular7

How to programmatically scroll to the end of scroll-viewport?


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?


Solution

  • 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);
        })
      }