使用cdk-virtual-scroll(角度8)滚动到底部 [英] Scroll to bottom with cdk-virtual-scroll (Angular 8)

查看:99
本文介绍了使用cdk-virtual-scroll(角度8)滚动到底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显示一条消息列表,并在收到新消息时滚动到底部,即使我在顶部也是如此.我希望即使在元素高度不同的情况下也可以完全滚动到底部.

Display a list of messages and scroll to the bottom when a new message is received, even when I am at the top. I would like to scroll fully bottom even with elements of different heights.

对于虚拟滚动,我必须设置 [itemSize] 属性,但是对我来说,这不是静态值:

With virtual scroll, I have to set the [itemSize] property, but for me it is not a static value:

  • 当一条消息太长而无法一行时,它会分成多行,因此其高度会发生变化.
  • 我有不同类型的消息,它们的高度不同(例如系统消息).

此外,我正在使用 ng-content 从父级插入按钮来加载以前的消息.我所看到的是,调用 _scrollToBottom 时,不是将我带到最低处,而是将我带到更高的位置.我怀疑这是因为虚拟滚动中元素的高度不同.

Also, I am using ng-content to insert a button from the parent to load previous messages. What I see is that, when _scrollToBottom is invoked, instead of taking me to the bottom, it takes me to a bit higher. I suspect this is because of the different heights of elements inside virtual-scroll.

我已经从Angular阅读了此自动调整大小滚动策略问题: https://github.com/angular/components/issues/10113; 但我不确定这是否可以解决我的问题.

I have read this autosize scroll strategy issue from Angular: https://github.com/angular/components/issues/10113; but I am not sure this will solve my problem.

任何关于我能做什么的想法都会受到欢迎.

Any idea of what I could do will be welcome.

代码框: https://codesandbox.io/s/angular-virtual-scroll-biwn6

  • 加载邮件后,向上滚动.
  • 发送消息.(加载新消息时,虚拟滚动不会滚动到底部,而是停止在更高的位置)
  • 重复

带有错误的视频: https://gofile.io/d/8NG9HD

Gourav Garg 提供的解决方案有效.只需执行两次滚动功能即可.

The solution given by Gourav Garg works. Simply by executing twice the scroll function.

我现在正在这样做:


  private _scrollToBottom() {
    setTimeout(() => {
      this.virtualScrollViewport.scrollTo({
        bottom: 0,
        behavior: 'auto',
      });
    }, 0);
    setTimeout(() => {
      this.virtualScrollViewport.scrollTo({
        bottom: 0,
        behavior: 'auto',
      });
    }, 50);
  }

我认为它不是很优雅,但是效果很好.

I think it is not very elegant but works fine.

推荐答案

如果您使用的是cdk,则可以使用>7

You can use if you are using cdk > 7

this.virtualScrollViewport.scrollToIndex(messages.length-1);

因为这将移至最后一项的顶部.您需要为该项目调用scrollIntoView.

As this will move to the top of last item. You need to call scrollIntoView for that item.

this.virtualScrollViewport.scrollToIndex(this.numbers.length - 1);
setTimeout(() => {
  const items = document.getElementsByClassName("list-item");
  items[items.length - 1].scrollIntoView();
}, 10);

<cdk-virtual-scroll-viewport #virtualScroll style="height: 500px" itemSize="90">
  <ng-container *cdkVirtualFor="let n of numbers">
    <li class="list-item"> {{n}} </li>
  </ng-container>
</cdk-virtual-scroll-viewport>

我已经更新了您的沙盒

这篇关于使用cdk-virtual-scroll(角度8)滚动到底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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