我在 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/