我有一个Angular应用程序,每当收到新消息时,我都会遇到自动滚动到聊天容器底部的问题。
我的模板
<div #msgContainer class="chat-box-body" appInfiniteScroll (scrollTop)="loadOlderMessages()">
<ng-container *ngFor="let msg of conversation.messages.edges">
<ng-container *ngIf="msg.node?.from?.id !== currentUser.id; else myMsg">
<div class="sender-msg-block">
<div class="wrapper-left">
<img class="sender-dp"
[src]="conversation.conversation_participants[0].conversable?.profile_picture?.url || 'assets/images/no-user.svg'">
<p class="sender-msg">{{msg.node.body}}</p>
<span class="sender-time">{{msg.node.created_at}}</span>
</div>
</div>
</ng-container>
<ng-template #myMsg>
<div #newMesssage class="receiver-msg-block">
<div class="wrapper-right">
<span class="receiver-time">{{msg.node.created_at}}</span>
<p class="receiver-msg">
{{msg.node.body}}
</p>
</div>
</div>
</ng-template>
</ng-container>
当我收到新消息时。此订阅将在此函数内触发:
listenIncomingMessages() {
this.chatService.messageReceived$
.pipe(
takeWhile(() => this.isAlive)
)
.subscribe((data: any) => {
if (data) {
const newEdge = {
node: data
};
if (data.conversation_id === this.conversationId) {
this.conversation.messages.edges = <any>[...this.conversation.messages.edges, newEdge];
// TODO: Scroll to bottom not working
this.msgContainer.nativeElement.scrollTop =
this.msgContainer.nativeElement.scrollTop + this.newMesssage.nativeElement.scrollHeight;
}
}
});
}
请帮助。谢谢:)
答案 0 :(得分:0)
使用ngAfterViewChecked
来帮助您使用此link
首先声明
@ViewChild('scrollMe') private myScrollContainer: ElementRef;
您的.ts文件中的。然后在ngOnInit()
中定义这两个函数,它们将检测组件中的变化并相应地向下滚动。
ngAfterViewChecked() {
this.scrollToBottom();
}
scrollToBottom(): void {
try {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
} catch (err) { }
}