可以运行角度区超出这个功能,以防止多余的变化检测周期。
对于我将覆盖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
也
见这并不与角4不幸的是工作。我得到这个TS建立自己的错误,因为addGlobalEventListener'的'定义改变。 – Dai