Search code examples
angularscrollangular-material

Angular scroll host listener not giving scroll values


In my app.component.html I have this setup:

<app-header *ngIf="navbarTop"></app-header>

<mat-drawer-container id="drawer-container">

    <mat-drawer mode="over" id="side-drawer" [opened]="isOpen">
        <div>
            <!-- Sidenav content -->
        </div>
    </mat-drawer>

    <!-- Main content of the site -->
    <mat-drawer-content id="scroller" (scroll)="scrollHandler($event)">
        <main class="container">
            <router-outlet></router-outlet>
        </main>
    </mat-drawer-content>

</mat-drawer-container>

<app-header *ngIf="!navbarTop"></app-header>

It's basically a giant mat-drawer for the sidenav so that every page can have access to the side menu, and the router-outlet in the main drawer/section of the site.

I've tried putting my (scroll) binding on the mat-drawer, main, and the router-outlet itself and having it there on the mat-drawer-content seems to be the best option so far. Now, on to the actual issue. My .ts has this in it:

@HostListener('window:scroll', ['$event']) 
    scrollHandler(e) {
      console.log("scrolled");
      console.log(window.scrollY);
      console.log(document.body.scrollTop);
    }

No matter how I go about this, both of the console logs are returning 0, but the event does fire. How can I get an actual scrollY/offsetY/scrollTop/whatever value?


Solution

  • Thanks to this post I was able to fix this issue using e.srcElement.scrollTop. If someone could explain why this works over the other things I've tried, that would be great, but at least there's an answer.