2016-07-07 36 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> 
相关问题