Scroll Top in angular2

58,553

Solution 1

import like this,

import { Inject} from "@angular/core";
import { DOCUMENT } from '@angular/platform-browser';

In your constructor add this,

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

Then you can set the scroll anywhere like this,

this.document.body.scrollTop = 0;

Solution 2

Just use:

window.scroll(0, 0);

Solution 3

I solved my angular scrolling problem using data binding:

<div class="container" [scrollTop]="scrollTop"> ... </div>

with the styles:

.container {
  height: 100%;
  scroll: auto;
  position: relative;
}

Solution 4

In app.component.ts

const mainDiv = document.getElementById('mainDIV');
mainDiv.scrollTop = 0;

In app.component.html

<div id="mainDIV" style="height: 100vh;overflow: auto;">
    <app-header></app-header>
    <router-outlet></router-outlet>
    <app-footer></app-footer>
</div>

Solution 5

I propose to write directive for that. Make sure to import it in the module you are using.

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[scrollToTop]'
})
export class ScrollToTopDirective {
  @HostListener('click')
  public onClick() {
    if (window && window.pageYOffset) {
      window.scroll(0, 0);
    }
  }
}

and use it like below

<button scrollToTop>Scroll to Top</button>

Consider also to add the prefix to the directive in compliance with Angular best practices.

https://angular.io/guide/styleguide#directive-custom-prefix

Share:
58,553
Vinodh Ram
Author by

Vinodh Ram

Website - https://vinodhram.com My Mobile - +91-9985279993 Mail - [email protected] LinkedIn - https://in.linkedin.com/in/vinodh-ram-14888167 Facebook - https://www.facebook.com/vinodh.ram.100 Twitter - https://twitter.com/vinodh_ram Instagram - https://www.instagram.com/vinodh.ram

Updated on September 17, 2020

Comments

  • Vinodh Ram
    Vinodh Ram over 3 years

    I am working on angular2 web application where I need help on the following. My page consists of multiple components. I want to scroll top of the page when user clicks a button. I tried document.body.scrollTop = 0; but this is not working in Chrome. I Tried document.documentElement.scrollTop=0;window.scrollTo(0, 0); but not working