ウェブサイト検索

javascript - Angular2でHostListenerを破棄する方法


私は、ページをスクロールするとアニメーションが発生するページを作成しています。要素がビューポートに表示されると、その対応するアニメーションが実行されます。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>

回答 #1

あなたの質問を完全には理解しているかどうかわかりません。特定のスクロール位置に到達したときにスクロールイベントのリスニングを停止したいということでしょうか?その場合は、ngOnInitで自分のリスナーを作成し、これらのイベントにもう興味がなくなったときにwindowから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を見てみるでしょう。なぜなら、これによってこの種のことが扱いやすくなるからです。

関連記事