Angular 2 Scroll to bottom (Chat style) Angular 2 Scroll to bottom (Chat style) angular angular

Angular 2 Scroll to bottom (Chat style)


I had the same problem, I'm using a AfterViewChecked and @ViewChild combination (Angular2 beta.3).

The Component:

import {..., AfterViewChecked, ElementRef, ViewChild, OnInit} from 'angular2/core'@Component({    ...})export class ChannelComponent implements OnInit, AfterViewChecked {    @ViewChild('scrollMe') private myScrollContainer: ElementRef;    ngOnInit() {         this.scrollToBottom();    }    ngAfterViewChecked() {                this.scrollToBottom();            }     scrollToBottom(): void {        try {            this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;        } catch(err) { }                     }}

The Template:

<div #scrollMe style="overflow: scroll; height: xyz;">    <div class="..."         *ngFor="..."        ...>      </div></div>

Of course this is pretty basic. The AfterViewChecked triggers every time the view was checked:

Implement this interface to get notified after every check of your component's view.

If you have an input-field for sending messages for instance this event is fired after each keyup (just to give an example). But if you save whether the user scrolled manually and then skip the scrollToBottom() you should be fine.


Simplest and the best solution for this is :

Add this #scrollMe [scrollTop]="scrollMe.scrollHeight" simple thing on Template side

<div style="overflow: scroll; height: xyz;" #scrollMe [scrollTop]="scrollMe.scrollHeight">    <div class="..."         *ngFor="..."        ...>      </div></div>

Here is the link for WORKING DEMO (With dummy chat app) AND FULL CODE

Will work with Angular2 and also upto 5, As above demo is done in Angular5.


Note :

For error : ExpressionChangedAfterItHasBeenCheckedError

Please check your css,it's a issue of css side,not the Angular side , One of the user @KHAN has solved that by removing overflow:auto; height: 100%; from div. (please check conversations for detail)


The accepted answer fires while scrolling through the messages, this avoids that.

You want a template like this.

<div #content>  <div #messages *ngFor="let message of messages">    {{message}}  </div></div>

Then you want to use a ViewChildren annotation to subscribe to new message elements being added to the page.

@ViewChildren('messages') messages: QueryList<any>;@ViewChild('content') content: ElementRef;ngAfterViewInit() {  this.scrollToBottom();  this.messages.changes.subscribe(this.scrollToBottom);}scrollToBottom = () => {  try {    this.content.nativeElement.scrollTop = this.content.nativeElement.scrollHeight;  } catch (err) {}}