2016-07-07 81 views
3

檢查用戶是否在沒有jQuery的情況下滾動到Angular2的頁面底部的最佳做法是什麼?我有權訪問我的應用程序組件中的窗口嗎?如果不是,我應該檢查滾動到頁腳組件的底部,我該怎麼做?頁腳組件上的指令?有沒有人完成這個?檢查用戶是否已滾動到Angular 2的底部

回答

8

//你可以使用它。

@HostListener("window:scroll", []) 
onScroll(): void { 
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) { 
     // you're at the bottom of the page 
    } 
} 
+0

只好寫爲@HostListener( 「窗口:滾動」,[]),使其工作。 – pabloruiz55

2

對我來說,我的客艙底部是不是在頁面的底部,所以我不能使用window.innerHeight來看看用戶滾動到客艙的底部。 (我的目標是始終滾動到聊天的底部,除非用戶試圖向上滾動)

我用下面的代替它完美地工作:

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

一些背景:

@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) { } 
} 

<div class="messages-box" #scrollMe (scroll)="onScroll()"> 
    <app-message [message]="message" *ngFor="let message of messages.slice().reverse()"></app-message> 
</div> 
相關問題