简体   繁体   English

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

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

For better performance, which syntax shoul'd i use in Angular 2+?为了获得更好的性能,我应该在 Angular 2+ 中使用哪种语法? Why use HostListener when is easy to get the scroll position with onscroll window event and pageYOffset?为什么在很容易获得带有 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); } }

It very simple, in one case you are adding some decorator property ( @HostListener ) on the component, on the other hand you are binding event directly to the window.它非常简单,在一种情况下,您在组件上添加一些装饰器属性( @HostListener ),另一方面,您将事件直接绑定到 window。

  1. Host listeners are destroyed when the component they belong to is destroyed, so no need to remove the event or unsubscribe it, it will be taken care by angular it self while component gets destroy.主机监听器在其所属的组件被销毁时被销毁,因此无需删除事件或取消订阅它,它会在组件被销毁时由 angular 自行处理。

  2. Attaching event to window, even component get destroyed, the event still there, it doesn't get unsubscribe automatically.将事件附加到 window,即使组件被破坏,事件仍然存在,它不会自动取消订阅。

That's one of the fair and clean advantage(more performant code) we have with host listener.这是我们与主机侦听器一起拥有的公平和干净的优势之一(更高性能的代码)。 You can check more on您可以查看更多

HostListener主机监听器

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

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