I have a div with overflow-y: scroll;
that is populated by an Observable.interval()
polling and basic {{content}}
interpolation.
I'm trying to have it automatically scrolled to the bottom, so the last line will always be visible.
I found this plnkr http://plnkr.co/edit/7yz2DUttPjI5GVJkvr5h?open=app%2Fapp.component.ts which looks like the most elegant solution:<div #list class="list" [scrollTop]="list.scrollHeight">
However when I try the same approach I get a Expression has changed after it was checked.
Exception.
<div class="cdiv" #cdiv [scrollTop]="cdiv.scrollHeight">{{content}}</div>
I can only assume that the *ngFor .. | async
from the plunker behaves differently internally than the direct interpolation I'm using.
However I don't understand exactly why and if there is a way to fix it.
Here is the most elegant solution in Angular:
Assign a variable to the div element that you want to scroll:
<div class="chat-messages" #container> <!-- Your content --> </div>
View the div in your Controller and call the scrollToBottom
method if you update the content of your container:
export class ChatComponent {
@ViewChild('container') container: ElementRef;
//...
private scrollToBottom() {
this.container.nativeElement.scrollTop = this.container.nativeElement.scrollHeight;
}
}
I hope, this helped.
Best,
Junus
I ended up finding an alternate solution which isn't quite as clean, but at least it works for now:
... implements AfterViewChecked
...
ngAfterViewChecked()
{
let d = document.querySelector('.cdiv');
if(d)
{
d.scrollTop = d.scrollHeight;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With