Angular 2滚动到底部(聊天样式) [英] Angular 2 Scroll to bottom (Chat style)

查看:80
本文介绍了Angular 2滚动到底部(聊天样式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ng-for循环中有一组单电池组件.

I have a set of single cell components within an ng-for loop.

我已经准备好一切,但我似乎找不到合适的

I have everything in place but I cannot seem to figure out the proper

当前我有

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

但是,由于图像以异步方式将视口向下推,所以这并非一直有效.

But this doesn't work all the time as images asynchronously push the viewport down.

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

Whats the appropriate way to scroll to the bottom of a chat window in Angular 2?

推荐答案

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

I had the same problem, I'm using a AfterViewChecked and @ViewChild combination (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>

当然,这是非常基本的.每次检查视图时,AfterViewChecked都会触发:

Of course this is pretty basic. The AfterViewChecked triggers every time the view was checked:

实施此界面,以便在每次检查组件视图后得到通知.

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

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

If you have an input-field for sending messages for instance this event is fired after each keyup (just to give an example). But if you save whether the user scrolled manually and then skip the scrollToBottom() you should be fine.

这篇关于Angular 2滚动到底部(聊天样式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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