如何用angular的材质虚拟滚动以编程方式滚动到项目? [英] How to programmatically scroll to item with angular's material virtual scroll?
问题描述
我有一个包含很多项目的列表,可以选择每个项目.为此,我使用了Angular Material Virtual Scroll.选择一个项目后,选中的项目将突出显示,然后保存在服务器上.当我刷新页面时,所选项目来自服务器,并再次突出显示.
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 and then is saved on the server. When I refresh the page, the selected item comes from the server and is again highlighted.
我的代码看起来像
<cdk-virtual-scroll-viewport itemSize="40" class="wrapper">
<div *cdkVirtualFor="let item of list"
[class.selected]="item.id === selectedItem.id">
</div>
</cdk-virtual-scroll-viewport>
问题在于,如果选择了列表中位于下方的项目,则该项目将突出显示,但是我必须向下滚动至列表才能看到它.当该项目来自服务器时,我想以编程方式向下滚动至它.
The problem is that if a select an item that is down in the list, it is highlighted, but I have to scroll down to the list to see it. I want to programmatically scroll down to it when that item comes from the server.
文档中有一个scrollToIndex
方法.在哪里可以找到FixedSizeVirtualScrollStrategy
的实例,因此可以调用此方法?
I the docs there is a scrollToIndex
method. Where I can find an instance of FixedSizeVirtualScrollStrategy
, so I can call this method?
推荐答案
当然,您需要获取对CdkVirtualScrollViewport
实例的引用.
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);
}
}
注意:这假定列表已在ngAfterViewInit
生命周期内加载.您尚未提供有关如何设置列表值的更多信息,所以这是我能提供的最好的信息.
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.
这篇关于如何用angular的材质虚拟滚动以编程方式滚动到项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!