gpt4 book ai didi

javascript - 如何销毁 Angular2 中的 HostListener

转载 作者:太空狗 更新时间:2023-10-29 19:28:24 31 4
gpt4 key购买 nike

我正在创建一个页面,向下滚动页面时会出现动画,当元素在视口(viewport)上可见时,会出现相应的动画。当我使用 Angular2 时,想到用它编写滚动函数。我搜索了一整天,发现 HostListener 可以满足我的需求。但是,我的问题是“已使用多个页面”。因此,我需要滚动功能只出现在所需的页面之一。有什么解决办法吗?

我还想到了一些可能的解决方案,如下所示:

  1. 我们可以摧毁监听器
  2. 为特定页面添加监听器

如果上面提到的是可能的,那么我们该怎么做。

我的代码:

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解决这个问题,因为它使这类事情更容易处理。

关于javascript - 如何销毁 Angular2 中的 HostListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46199333/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com