How to programmatically scroll to item with angular's material virtual scroll?

被刻印的时光 ゝ 提交于 2019-12-01 04:02:51

Sure, you will need to get a reference to the CdkVirtualScrollViewport instance.

@ViewChild(CdkVirtualScrollViewport) viewPort: CdkVirtualScrollViewport;

scrollToMiddle(){
  this.viewPort.scrollToIndex(list.length/2, "smooth");
}

An example can be found in this stackblitz

For the requirement of scrolling to the index of the selected element in the list, you could do the following:

ngAfterViewInit(){
  const selectedIndex = this.list.findIndex(elem => elem.id === this.selectedItem.id);
   if(selectedIndex > -1){
     this.viewPort.scrollToIndex(selectedIndex);
   }
}

Note: this assumes that the list is already loaded during the ngAfterViewInit lifehook. As you havent provided more information about how the list value is set, this is the best that I can provide.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!