18

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

5
  • 1
    document.body.scrollTop = 0; should work, anyways whats the error ? Commented Apr 29, 2017 at 5:36
  • It is not giving errors. but it is not working in chrome Commented Apr 29, 2017 at 5:37
  • can you create your problem on plunker ? Commented Apr 29, 2017 at 5:40
  • can you at least show us how you bind the event and how long is your page? Commented Apr 29, 2017 at 5:44
  • let ele = document.querySelector('.informationBdrCmpt') as HTMLElement; ele.scrollTop(0); is not working. Any help. ......Getting error as [ts] Cannot invoke an expression whose type lacks a call signature. Type 'Number' has no compatible call signatures. Commented Oct 22, 2018 at 14:18

9 Answers 9

22

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;
Sign up to request clarification or add additional context in comments.

7 Comments

Importing from @angular/platform-browser seems to be deprecated, it's suggested to import from @angular/common instead. link
This does not seem to work. No errors, just non-responsive, using Angular 4/CLI.
For me it did work in Angular 2 (even without injecting DOCUMENT). Just updated to Angular 5.0.3 and tried above solution and for me it doesn't work.
EDIT: Just realised it has to do with some update of Chrome. It works fine in Safari and it doesn't work in Chrome, neither with Angular2 (where it did work before) nor in Angular 5.
If you are using Angular CLI Use 2nd answer it worked for me
|
10

Just use:

window.scroll(0, 0);

Comments

6

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

1 Comment

This was my preferred answer, but keep in mind, if the value of scrollTop doesn't change in the component, you won't see anything happen. For instance if you set the default value to 0 in the component, scroll the page, and then set it to zero after a button click or something.
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

2 Comments

You are right, it is not needed. Removed it. Thanks.
That is fine) Thanks. I think it is good to ensure the quality in code snippets like that. In IDE such things are spotted really quickly so I need to get used to spot such things here.
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>

Comments

1

Please use below code. For my case

this.document.body.scrollTop = 0

not working but

this.document.documentElement.scrollTop = 0

working. So may be some browser dependency.

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

constructor(@Inject(DOCUMENT) private document: Document) { }
this.document.documentElement.scrollTop = 0;

Comments

1

html code :

<div class="scroll-to-top" [ngClass]="{'show-scroll': navIsFixed}">
            <button (click)="scrollToTop()">
                Top
            </button>
        </div>

css code:

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

ts code:

import {Component, OnInit, Inject, HostListener} from '@angular/core';
import { DOCUMENT } from "@angular/platform-browser";
import { BrowserModule } from '@angular/platform-browser';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Hard Hitter@Cool';
  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));
          }
      })();
  }

}

Comments

0

If it is not window scroll, but just div with his own scroll, this should work:

Gloabal service WindowRef:

import { Injectable } from '@angular/core';

function _window(): any {
  // return the global native browser window object
  return window;
}

@Injectable()
export class WindowRef {
  get nativeWindow(): any {
    return _window().document;
  }
}

Add it to constructor:

constructor(private winRef: WindowRef) {}

And in the code, where you want to put it just add this line:

this.winRef.nativeWindow.getElementsByClass('nameOfClass')[0].scroll(0, 0);

Of course you can also use other selectors like: getElementByTagName, getElementById, getElementByName ...

Comments

0

Inject this argument into your constructor: @Inject(DOCUMENT) private document: Document

Then, call scrollIntoView function:

this.document.body.scrollIntoView({
   block: 'start',
   behavior: 'smooth'
});

Ready!! :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.