Scroll Event at Angular Universal

2019/2/11 min read
bookmark this
Responsive image

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