繁体   English   中英

Angular 2+ 使用 HostListener 或 window.pageYOffset 滚动?

[英]Angular 2+ scroll with HostListener or window.pageYOffset?

为了获得更好的性能,我应该在 Angular 2+ 中使用哪种语法? 为什么在很容易获得带有 onscroll window 事件和 pageYOffset 的滚动 position 时使用 HostListener?

 @HostListener('window:scroll', ['$event']) onWindowScroll($event) { this.scrollPosition = $event.target.children[0].scrollTop; console.log("scrollPosition:" + this.scrollPosition) };

 ngAfterViewInit(){ window.onscroll = function() { var currentScrollPos = window.pageYOffset; console.log("current:" + currentScrollPos); } }

它非常简单,在一种情况下,您在组件上添加一些装饰器属性( @HostListener ),另一方面,您将事件直接绑定到 window。

  1. 主机监听器在其所属的组件被销毁时被销毁,因此无需删除事件或取消订阅它,它会在组件被销毁时由 angular 自行处理。

  2. 将事件附加到 window,即使组件被破坏,事件仍然存在,它不会自动取消订阅。

这是我们与主机侦听器一起拥有的公平和干净的优势之一(更高性能的代码)。 您可以查看更多

主机监听器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM