Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 auto scroll div to bottom - Expression changed exception

Tags:

angular

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.

like image 515
TommyF Avatar asked Nov 04 '16 09:11

TommyF


2 Answers

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

like image 64
user7646788 Avatar answered Oct 23 '22 09:10

user7646788


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;
    }
}
like image 2
TommyF Avatar answered Oct 23 '22 10:10

TommyF