patterntypescriptangularCritical
Angular 2 Scroll to bottom (Chat style)
Viewed 0 times
angularchatstylescrollbottom
Problem
I have a set of single cell components within an
I have everything in place but I cannot seem to figure out the proper
Currently I have
But this doesn't work all the time as images asynchronously push the viewport down.
Whats the appropriate way to scroll to the bottom of a chat window in Angular 2?
ng-for loop.I have everything in place but I cannot seem to figure out the proper
Currently I have
setTimeout(() => {
scrollToBottom();
});But this doesn't work all the time as images asynchronously push the viewport down.
Whats the appropriate way to scroll to the bottom of a chat window in Angular 2?
Solution
I had the same problem, I'm using a
The Component:
The Template:
Of course this is pretty basic. The
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
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:
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.Code Snippets
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) { }
}
}<div #scrollMe style="overflow: scroll; height: xyz;">
<div class="..."
*ngFor="..."
...>
</div>
</div>Context
Stack Overflow Q#35232731, score: 290
Revisions (0)
No revisions yet.