首页 > 解决方案 > 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;
}

对应的相关h​​tml:

<ng-container *ngFor="let message of activeChatExchange.messages">

这行得通,但我必须引入睡眠才能使其工作。没有睡眠,更新scrollTop太快,下一页的窗口不会更新到滚动到底部。这与两者的价值无关scrollHeight。如果我设置一个非常高的静态数字,例如 999999,它仍然不会滚动到底部。

所以问题是这个解决方案不是很好。睡眠数字太高会在我的应用程序中人为延迟,使其显得迟缓,数字太低可能会导致慢速浏览器在加载后无法向下滚动。

我想在 DOM 事件更改完成时订阅,但仅限于activeChatExchange. 我应该如何处理这个?

标签: angular

解决方案


我想我在 Angular 的帮助下找到了解决方案- 等待 ngFor 更新 DOM

我不完全确定这是否是一个合适的解决方案,但将睡眠设置为 0 显然有效,因为函数超时在渲染后开始计数,这正是我想要的。

所以我的代码变成了

    this.updateMessageExchange.subscribe((interlocutor: MessageExchange) => {
        this.activeChatExchange = interlocutor;
        setTimeout(() => {
            this.scrollToBottom();
        }, 0);
    });

推荐阅读