Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user has scrolled to the bottom in Angular 2

What is the best practice to check if user has scrolled to the bottom of the page in Angular2 without jQuery? Do I have access to the window in my app component? If not should i check for scrolling to the bottom of the footer component, and how would I do that? A directive on the footer component? Has anyone accomplished this?

like image 510
C. Kearns Avatar asked Jul 07 '16 16:07

C. Kearns


3 Answers

// You can use this.

@HostListener("window:scroll", [])
onScroll(): void {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        // you're at the bottom of the page
    }
}
like image 133
mayur Avatar answered Sep 24 '22 00:09

mayur


For me the bottom of my chatbox wasn't at the bottom of the page, so I couldn't use window.innerHeight to see if the user scrolled to the bottom of the chatbox. (My goal was to always scroll to the bottom of the chat unless the user is trying to scroll up)

I used the following instead which worked perfectly:

let atBottom = element.scrollHeight - element.scrollTop === element.clientHeight

some context:

@ViewChild('scrollMe') private myScrollContainer: ElementRef;
disableScrollDown = false

 ngAfterViewChecked() {
    this.scrollToBottom();
}

private onScroll() {
    let element = this.myScrollContainer.nativeElement
    let atBottom = element.scrollHeight - element.scrollTop === element.clientHeight
    if (this.disableScrollDown && atBottom) {
        this.disableScrollDown = false
    } else {
        this.disableScrollDown = true
    }
}


private scrollToBottom(): void {
    if (this.disableScrollDown) {
        return
    }
    try {
        this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
    } catch(err) { }
}

and

<div class="messages-box" #scrollMe (scroll)="onScroll()">
    <app-message [message]="message" *ngFor="let message of messages.slice().reverse()"></app-message>
 </div>
like image 23
robert king Avatar answered Sep 24 '22 00:09

robert king


Rather than using document.body.offsetHeight use this:

if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) { // you're at the bottom of the page }

like image 29
Aditya Avatar answered Sep 27 '22 00:09

Aditya