2/1/2019

Scroll Event at Angular Universal

✓Angular2

Clone Universal starter project

First, we'll need to create angular universal app, you can clone from this universal-starter.

Wrong way to add window.addEventListener("scroll")

Following will be able to run at angular app, but will get error on angular universal server-side rendering.


  ngOnInit() {
    window.addEventListener("scroll", this.scrollEvent, true);
  }

  ngOnDestroy() {
    window.removeEventListener("scroll", this.scrollEvent, true);
  }

  scrollEvent = (event: any): void => {
    const number = event.srcElement.scrollTop;
    console.info(number);
  };

use HostListener from angular/core

Following code will able to run on both Angular app and Angular Universal server side rendering.


  @HostListener("window:scroll", []) onWindowScroll() {
    // do some stuff here when the window is scrolled
    const verticalOffset =
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop ||
      0;

    console.info(verticalOffset);
  }

Relative Blogs