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

后端 未结 1 1484
礼貌的吻别
礼貌的吻别 2021-01-11 11:48

I have a list that has many items and each item can be selected. For this I use Angular Material Virtual Scroll. When an item is selected, the selected item is highlighted a

相关标签:
1条回答
  • 2021-01-11 12:00

    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.

    0 讨论(0)
提交回复
热议问题