Reputation: 511
Need to scroll to bottom automatically once messages are being added in a chat.
Tried AfterViewChecked method of implementing this, as suggessted in [angular2 scroll to bottom (chat style) - It works fine as it makes the scroll move to bottom. But when we try scrolling up as soon as we add a message in the chat, it is not allowing and it again pushes the view to the bottom of the chat
Please suggest a workaround on this.
Upvotes: 2
Views: 3434
Reputation: 2323
The below code worked for me for my angular 4 chat application
My component.html
<div class="feedBody" #scrollMe (scroll)="onScroll()" >
<div class="feedList">
</div>
</div>
My component.css
.feedBody {
height: 235px;
overflow-y: auto;
}
My component.ts
scrollToBottom():void{
if (this.disableScrollDown) {
return
}
try {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
} catch(err) { }
}
onScroll(){
let element = this.myScrollContainer.nativeElement;
let atBottom = (element.scrollTop+200) >= (element.scrollHeight - element.offsetHeight);
if (atBottom) {
this.disableScrollDown = false
} else {
this.disableScrollDown = true
}
}
I was using element.scrollTop+200
because I wanted a behaviour where I should not compulsorily present at the bottom of the screen but can be a little top by 200px.
Hope it works for you.
Upvotes: 1