Updated on Kisan Patel
Problem:
How to implement auto scroll of chat messages in Angular?
Solution
The AfterViewChecked
triggers every time the view was checked. just implement this interface to get notified after every check of your component’s view.
Component (discussion.component.ts)
import {..., AfterViewChecked, ElementRef, ViewChild, OnInit} from '@angular/core'; @Component({ selector: 'app-discussion', templateUrl: './discussion.component.html', styleUrls: ['./discussion.component.css'] }) export class DiscussionComponent 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) { } } }
Html Templete (discussion.component.html)
<div #scrollMe style="overflow: scroll; height: xyz;"> <div class="..." *ngFor="..." ...> </div> </div>