如何在Angular2中销毁HostListener

问题描述 投票:0回答:2

我正在创建一个页面,其中向下滚动页面时将发生动画,当元素在视口上可见时,将发生相应的动画。当我使用 Angular2 时,想到使用它来编写 scroll 函数。我搜索了一整天,发现 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>
javascript html angular typescript angular2-template
2个回答
2
投票

我不确定我完全理解你的问题。您是否想在到达某个滚动点时停止监听滚动事件?在这种情况下,只需在 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 来解决这个问题,因为它使这类事情更容易处理。


0
投票

我建议使用 rxjs:

import { fromEvent, Subscription } from 'rxjs';

在组件中添加全局

clickSubscription: Subscription
;然后在
ngOnInit
你可以这样做:

  ngOnInit(): void {
    this.clickSubscription = fromEvent(document, 'click').subscribe(event => {
       console.log(event);
    })
   }

ngOnDestroy

  ngOnDestroy(): void {
    this.clickSubscription.unsubscribe();
}
© www.soinside.com 2019 - 2024. All rights reserved.