Scroll to top with Angular 4 using @HostListener

Add this to your component TypeScript file.

import { Component, OnInit, Inject, HostListener } from '@angular/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 (click)="scrollToTop()">
        Top
    </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
Showing 2 comments
  • Doru
    Reply

    It works but its too advanced for me :))

    The icon throws an error because it’s material design.

    I may be able to use this as inspiration for my problem so.. thanks.

    I will try to understand it haha

    tl:dr Awesome solution Chris, thank you.

    • Chris
      Chris
      Reply

      Sorry about that! I haven’t had the time to write up a nice description of how to use it.

      You can replace the md-icon with your own icon and it should work fine without Angular Material. I updated the post without the material tags to make it more user-friendly.

Leave a Comment