[英]How to destroy HostListener in Angular2
我正在创建一个页面,其中向下滚动页面时会发生动画,当元素在视口上可见时,将发生相应的动画。 当我使用Angular2时,考虑使用它编写滚动函数 。 我搜索了一整天,发现HostListener将满足我的要求。 但是,我的问题是“已经使用了多个页面”。 因此,我需要滚动功能只发生一个所需的页面。 对此有什么解决方案吗?
我还想到了列出的一些可能的解决方案:
如果上述可能,那么我们怎么做呢。
我的代码:
import {Component,HostListener} from '@angular/core';
@Component({
selector: 'my-app',
templateUrl:'src/html/home.html',
})
export class Home {
@HostListener('window:scroll', ['$event'])
onScroll(e){
// My animation code
}
}
HTML代码:
<div (window:resize)="onResize($event)">
//some code
</div>
我不确定我完全理解你的问题。 当您到达某个滚动点时,是否要停止收听滚动事件? 在这种情况下,只需在ngOnInit中创建自己的侦听器,并在不再对这些事件感兴趣时在窗口上调用removeEventListener。
import {Component,HostListener} from '@angular/core';
@Component({
selector: 'my-app',
templateUrl:'src/html/home.html',
})
export class Home {
private boundScrollCallback: Function;
ngOnInit() {
/**
* Need to bind the onScroll function so that "this" in
* onScoll will result in the component instance itself.
* Otherwise this.removeScrollLiteners() will not work in that context.
*/
this.boundScrollCallback = this.onScroll.bind(this);
window.addEventListener('scroll', this.boundScrollCallback);
/**
* Need this as well as resizing the window may result
* in a change of scroll position.
*/
window.addEventListener('resize', this.boundScrollCallback);
}
onScroll(e){
if (true /** Logic to check scroll position goes here */) {
// Animation code
this.removeScrollLiteners(); // Stop listening for events.
}
}
/**
* Remove the event listeners.
*/
private removeScrollLiteners() {
window.removeEventListener('scroll', this.boundScrollCallback);
window.removeEventListener('resize', this.boundScrollCallback);
}
ngOnDestroy() {
this.removeScrollLiteners(); // Stop listening for events.
}
}
否则我会看看IntersectionObserver来解决这个问题,因为它使这些事情更容易处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.