Scroll up to angular2

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

+6
source share
5 answers

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,

this.document.body.scrollTop = 0;
+14
source

I solved the angular scroll problem using data binding:

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

with styles:

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

app.component.ts

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

app.component.html

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

I suggest writing a directive for this. Be sure to import it into the module you are using.

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

@Directive({
  selector: '[scrollToTop]'
})
export class ScrollToTopDirective {
  constructor(private elementRef: ElementRef) {
  }

  @HostListener('click')
  public onClick() {
    if (window && window.pageYOffset) {
      window.scroll(0, 0);
    }
  }
}

and use it as below

<button scrollToTop>Scroll to Top</button>
0
source

Just use:

window.scroll(0, 0);
0
source

Source: https://habr.com/ru/post/1016874/


All Articles