Scroll to top with Angular 4 using @HostListener

Add this to your component TypeScript file.

import { Component, OnInit, Inject, HostListener } from [email protected]/core';
import { DOCUMENT } from "@angular/platform-browser";

@Component({
    selector: 'app',
    template: require('./app.component.html'),
    styles: [require('./app.component.css')]
})
export class AppComponent implements OnInit {
    navIsFixed: boolean;

    constructor(@Inject(DOCUMENT) private document: Document) { }

    @HostListener("window:scroll", [])
    onWindowScroll() {
        if (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop > 100) {
            this.navIsFixed = true;
        } else if (this.navIsFixed && window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop < 10) {
            this.navIsFixed = false;
        }
    }

    scrollToTop() {
        (function smoothscroll() {
            var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
            if (currentScroll > 0) {
                window.requestAnimationFrame(smoothscroll);
                window.scrollTo(0, currentScroll - (currentScroll / 5));
            }
        })();
    }

    ngOnInit(): void {
    }
}

Add this to your component html.

<!--Scroll to top-->
<div class="scroll-to-top" [ngClass]="{'show-scroll': navIsFixed}">
    <button md-fab (click)="scrollToTop()">
        <md-icon>keyboard_arrow_up</md-icon>
    </button>
</div>

Add this to your component CSS.

.scroll-to-top {
    position: fixed;
    bottom: 15px;
    right: 15px;
    opacity: 0;
    transition: all .2s ease-in-out;
}

.show-scroll {
    opacity: 1;
    transition: all .2s ease-in-out;
}
Recent Posts

Leave a Comment