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

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

问题描述

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

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

目前我有

setTimeout(() => {滚动到底部();});

但这并不总是有效,因为图像异步地将视口向下推.

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

解决方案

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

组件:

import {..., AfterViewChecked, ElementRef, ViewChild, OnInit} from 'angular2/core'@成分({...})导出类 ChannelComponent 实现 OnInit, AfterViewChecked {@ViewChild('scrollMe') 私有 myScrollContainer: ElementRef;ngOnInit() {this.scrollToBottom();}ngAfterViewChecked() {this.scrollToBottom();}滚动到底部():无效{尝试 {this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;}赶上(错误){}}}

模板:

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

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

<块引用>

实现此接口以在每次检查组件视图后收到通知.

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

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

Currently I have

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

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

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

解决方案

I had the same problem, I'm using a AfterViewChecked and @ViewChild combination (Angular2 beta.3).

The Component:

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) { }                 
    }
}

The Template:

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

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.

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天全站免登陆