我正在尝试在Angular 9 PWA中构建一个聊天组件。现在,我想知道当在聊天窗口中显示新消息时如何实现“ 自动滚动到底部”功能。
为此,我创建了一个自定义ScrollToBottom指令
并将其应用于聊天DIV容器。<div class="msg_history" scrollToBottom> <li class="message" *ngFor="let message of messages | async">
在此指令中,我有一个名为scrollToBottom的方法。
public scrollToBottom() { const el: HTMLDivElement = this._el.nativeElement; setTimeout(() => el.scrollTop = Math.max(0, el.scrollHeight - el.offsetHeight)); }
现在,我的问题是,在“会话主题”收到一条新消息后,是否有可能(以及如何?)从“聊天”组件中调用指令的方法。
//In component this.chatService.conversation.subscribe(() => DIRECTIVE.scrollToBottom());
或者,最好是省略聊天组件并将聊天服务直接注入到指令中,以便在那里处理会话主题更改?
@Directive({ selector: '[scrollToBottom]' }) export class ScrollToBottomDirective { constructor(private _el: ElementRef, private chat: ChatService) { } public ngAfterViewInit() { this.chat.conversation.subscribe(() => this.scrollToBottom()); } public scrollToBottom() { const el: HTMLDivElement = this._el.nativeElement; setTimeout(() => el.scrollTop = Math.max(0, el.scrollHeight - el.offsetHeight)); } }
谢谢你前进;-)
我正在尝试在Angular 9 PWA中构建一个聊天组件。现在,我想知道当聊天窗口中显示新消息时如何实现“自动滚动到底部”功能。对于...