简体   繁体   中英

Scroll Top in angular2

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

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;

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

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>

只需使用:

window.scroll(0, 0);

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

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;

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM