scroll - Angular 2滚动到底部(聊天风格)

标签 scroll typescript angular

我在 ng-for 循环中有一组单细胞组件。

我已经准备好了一切,但我似乎无法找出合适的

目前我有

setTimeout(() => {
  scrollToBottom();
});

但这并不总是有效,因为图像会异步地将视口(viewport)向下推。

在 Angular 2 中滚动到聊天窗口底部的合适方法是什么?

最佳答案

我遇到了同样的问题,我使用的是 AfterViewChecked@ViewChild组合(Angular2 beta.3)。

组件:

import {..., AfterViewChecked, ElementRef, ViewChild, OnInit} from 'angular2/core'
@Component({
    ...
})
export class ChannelComponent implements OnInit, AfterViewChecked {
    @ViewChild('scrollMe') private myScrollContainer: ElementRef;

    ngOnInit() { 
        this.scrollToBottom();
    }

    ngAfterViewChecked() {        
        this.scrollToBottom();        
    } 

    scrollToBottom(): void {
        try {
            this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
        } catch(err) { }                 
    }
}

模板:

<div #scrollMe style="overflow: scroll; height: xyz;">
    <div class="..." 
        *ngFor="..."
        ...>  
    </div>
</div>

当然这是非常基本的。每次检查 View 时都会触发 AfterViewChecked:

Implement this interface to get notified after every check of your component's view.

例如,如果您有一个用于发送消息的输入字段,则在每次键入后都会触发此事件(仅举个例子)。但是,如果您保存用户是否手动滚动,然后跳过 scrollToBottom(),您应该没问题。

关于scroll - Angular 2滚动到底部(聊天风格),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232731/

相关文章:

Jquery 滚动 1 div 其他 div 向后滚动

jquery - 悬停滚动,点击速度

java - 滚动 ListView 时 TextView 中的数据切换

angular - Ionic 4 - ionic 选择不会滚动到警报中的选定项目

reactjs - Typescript 和 React 具有复杂的 prop 类型接口(interface)

javascript - 为什么 Date.now() | 0 与 Date.now() 不同

javascript - 类型 'catch' 上不存在属性 'Observable<IEmployee[]>'

javascript - 无法从 Angular 5 和 Dragula 制作多个内部可拖动对象

javascript - 为什么这里需要 'this' 关键字?它指的是什么?

angular - 如何对 IntervalObservable 进行单元测试