2017-07-21 37 views
3

我有一个hostListner监听我的Angular2应用程序中的滚动事件。我正在使用它来检查用户是否滚动到页面的底部,并在用户到达页面底部时执行方法。我已经构建了hostlistner以下列方式:HostListener减慢应用程序:Angular2

@HostListener('window:scroll', []) 
    onWindowScroll() { 
    const scrolledPercent = /* some logic to calculate the percentage scrolled */ 
    if (condition1 && condition2 ....) 
    { 
    // doing something here 
    } 
    } 

但这减缓我的应用程序,而不是在一个非常显著的方式,但页面上的滚动不再顺畅。也许是因为hostlistner一直在寻找滚动页面,所以订阅会让整个滚动体验变得迟缓。我尝试删除hostListner并再次顺利滚动。有没有人注意到这种行为?如果不是,使用Angular2在页面上订阅滚动事件的最佳方式是什么?

回答

6

可以运行角度区超出这个功能,以防止多余的变化检测周期。

对于我将覆盖EventManager让听者区外。

自定义事件manager.ts

import { Injectable, Inject, NgZone } from '@angular/core'; 
import { EVENT_MANAGER_PLUGINS, EventManager } from '@angular/platform-browser'; 

@Injectable() 
export class CustomEventManager extends EventManager { 
    constructor(@Inject(EVENT_MANAGER_PLUGINS) plugins: any[], private zone: NgZone) { 
    super(plugins, zone); 
    }  

    addGlobalEventListener(element: HTMLElement, eventName: string, handler: Function): Function { 
    if(eventName.endsWith('out-zone')) { 
     eventName = eventName.split('.')[0]; 
     return this.zone.runOutsideAngular(() => 
      super.addGlobalEventListener(element, eventName, handler)); 
    } 

    return super.addGlobalEventListener(element, eventName, handler); 
    } 
} 

app.module.ts

... 
    providers: [ 
    { provide: EventManager, useClass: CustomEventManager } 
    ] 
}) 
export class AppModule {} 

和更新视图只有通过调用changeDetector.detectChanges

@HostListener('window:scroll.out-zone', []) // notice out-zone 
onWindowScroll() { 
    const scrolledPercent = /* some logic to calculate the percentage scrolled */ 
    if (condition1 && condition2 ....) { 
     this.cd.detectChanges(); 
    } 
} 

Plunker Example

+0

见这并不与角4不幸的是工作。我得到这个TS建立自己的错误,因为addGlobalEventListener'的'定义改变。 – Dai