Angular window scroll event using @HostListener

From: http://brianflove.com/2016/10/10/angular-2-window-scroll-event-using-hostlistener/
Author: Brian Love

The @HostListener Decorator

I couldn’t find too much information about the @HostListener
decorator in the docs, only the interface specification in the API. But, what I was able to learn via other blogs and questions on stack overflow is that the HostListener enables us to listen for events on the host, and to specify the values that are passed as arguments to the decorated function or class.
In this example I want to listen for the window’s scroll event. Here is the simple markup for this:

import { HostListener } from "@angular/core";

@HostListener("window:scroll", [])
onWindowScroll() {
 //we will do some stuff here when the window is scrolled
}

Inject Document object

In order to determine the body’s scrollTop value we need to inject the Document object. To do this, Angular 2 has provided a DOCUMENT dependency injection (DI) token to get the application’s rendering context, and when rendering in the browser, this is the browser’s document object.

import { Inject } from "@angular/core";
import { DOCUMENT } from "@angular/platform-browser";

export class MyComponent{
  constructor(@Inject(DOCUMENT) private document: Document) { }
}

First, I import the Inject decorator as well as the DOCUMENT DI token. Then, in my component’s constructor function I can inject the Document object. Now that I have the document, I can use this to easily determine the scrollTop value in my onWindowScrolled()method.

Here is what my component looks like:

import { Component, HostListener, Inject, OnInit } from "@angular/core";
import { DOCUMENT } from '@angular/platform-browser';

@Component({
  template: `
    <div #target [class.fixed]="isFixed"></div>
  `
  styles: [ `
      .fixed{
        position: fixed !important;
        top: 0 !important;
      }
    `
  ]
})
export class MyComponent implements OnInit {

  public isFixed: boolean = false;

  constructor(
    @Inject(DOCUMENT) private document: Document,
    @ViewChild('target') private targetElement: ElementRef
  ) { }

  ngOnInit() { }

  @HostListener("window:scroll", [])
  onWindowScroll() {
    let targetPos= this.targetElement.nativeElement.offsetTop;
    let windowScrollPos = this.document.body.scrollTop;
    if (windowScrollPos > targetPos) {
      this.isFixed = true;
    } else {
      this.isFixed = false;
    }
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容