美文网首页我爱编程
Angular window scroll event usin

Angular window scroll event usin

作者: RoyTien | 来源:发表于2017-07-02 19:10 被阅读2271次

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;
    }
  }
}

相关文章

网友评论

    本文标题:Angular window scroll event usin

    本文链接:https://www.haomeiwen.com/subject/fwhocxtx.html