大佬教程收集整理的这篇文章主要介绍了HostListener减慢了应用程序:Angular2,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@HostListener('window:scroll',[]) onWindowScroll() { const scrolledPercent = /* some logic to calculate the percentage scrolled */ if ( condition1 && condition2 .... ) { // doing something here } }
但这会减慢我的应用程序速度,而不是以非常重要的方式,但页面上的滚动不再平滑.也许是因为hostlistner一直在寻找要滚动的页面,因此订阅会使整个滚动体验变得迟钝.我尝试删除hostListner,滚动再次平滑.有人注意到这种行为吗?如果没有,使用Angular2在页面上订阅滚动事件的最佳方法是什么?
为此,我将覆盖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,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(); } }
也可以看看
以上是大佬教程为你收集整理的HostListener减慢了应用程序:Angular2全部内容,希望文章能够帮你解决HostListener减慢了应用程序:Angular2所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。