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;
    }
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容