如何以编程方式滚动到带有 angular 材质虚拟滚动的项目? [英] How to programmatically scroll to item with angular's material virtual scroll?

查看:29
本文介绍了如何以编程方式滚动到带有 angular 材质虚拟滚动的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含很多项目的列表,每个项目都可以选择.为此,我使用 Angular Material Virtual Scroll.当一个项目被选中时,选中的项目会突出显示,然后保存在服务器上.当我刷新页面时,所选项目来自服务器并再次突出显示.

我的代码看起来像

<div *cdkVirtualFor="让列表项"[class.selected]="item.id === selectedItem.id">

</cdk-virtual-scroll-viewport>

问题是,如果选择列表中向下的项目,它会突出显示,但我必须向下滚动到列表才能看到它.当该项目来自服务器时,我想以编程方式向下滚动到它.

我在 docs 有一个 scrollToIndex方法.在哪里可以找到 FixedSizeVirtualScrollStrategy 的实例,以便我可以调用此方法?

解决方案

当然,您需要获得对 CdkVirtualScrollViewport 实例的引用.

@ViewChild(CdkVirtualScrollViewport) viewPort: CdkVirtualScrollViewport;滚动到中间(){this.viewPort.scrollToIndex(list.length/2, "smooth");}

一个例子可以在在这个stackblitz中找到

对于滚动到列表中所选元素的索引的要求,您可以执行以下操作:

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

注意:这假设列表已经在 ngAfterViewInit 生命周期中加载.由于您尚未提供有关如何设置列表值的更多信息,这是我能提供的最好的信息.

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.

My code looks like

<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.

I the docs there is a scrollToIndex method. Where I can find an instance of FixedSizeVirtualScrollStrategy, so I can call this method?

解决方案

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.

这篇关于如何以编程方式滚动到带有 angular 材质虚拟滚动的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆