angular - Angular - 等待特定变量的 DOM 更新视图
问题描述
我正在创建一个聊天应用程序。在更改聊天窗口时,我希望滚动条导航到底部以便立即查看最新消息。我这样做的代码:
ngAfterViewInit(): void {
this.updateMessageExchange.subscribe((interlocutor: MessageExchange) => {
this.activeChatExchange = interlocutor; // this triggers a view change in the html
setTimeout(() => {
console.log('sleep');
this.scrollToBottom();
}, 100);
});
}
private scrollToBottom(): void {
this.chatBoard.nativeElement.scrollTop = this.chatBoard.nativeElement.scrollHeight;
}
对应的相关html:
<ng-container *ngFor="let message of activeChatExchange.messages">
这行得通,但我必须引入睡眠才能使其工作。没有睡眠,更新scrollTop
太快,下一页的窗口不会更新到滚动到底部。这与两者的价值无关scrollHeight
。如果我设置一个非常高的静态数字,例如 999999,它仍然不会滚动到底部。
所以问题是这个解决方案不是很好。睡眠数字太高会在我的应用程序中人为延迟,使其显得迟缓,数字太低可能会导致慢速浏览器在加载后无法向下滚动。
我想在 DOM 事件更改完成时订阅,但仅限于activeChatExchange
. 我应该如何处理这个?
解决方案
我想我在 Angular 的帮助下找到了解决方案- 等待 ngFor 更新 DOM
我不完全确定这是否是一个合适的解决方案,但将睡眠设置为 0 显然有效,因为函数超时在渲染后开始计数,这正是我想要的。
所以我的代码变成了
this.updateMessageExchange.subscribe((interlocutor: MessageExchange) => {
this.activeChatExchange = interlocutor;
setTimeout(() => {
this.scrollToBottom();
}, 0);
});
推荐阅读
- sql - SQL Server FORMAT()函数参数问题
- python - Python函数关键字参数中的单前导下划线
- java - 为什么 Inet6Address.getByAddress 需要主机名和直接地址字节?
- c++ - 内置类型 default-value-initialization 的区别
- c# - 为什么 Autofac 的动态实例化 (Func ) 的隐式关系类型尊重生命周期范围?
- ios - SwiftUI:ForEach 无法推断复杂的闭包返回类型
- sas - SAS 并行运行两个数据步骤
- python - 如何重定向到我使用 urllib.request 下载的文件,以便用户在我的烧瓶应用程序上查看?
- kubernetes - 有没有办法在不使用入口/网关的情况下在 kubernetes 服务级别上设置金丝雀或加权部署?
- javascript - Flow js谓词函数