Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 | window.scrollTo(); is not working properly

Currently, I'm trying to automatically scroll to the top of the HTML page for which I'm using in my Typescript.

 window.scrollTo(0 , 0);

and while trying to automatically scroll down to bottom of the HTML page

 window.scrollTo( 0 , document.body.scrollHeight);
  • I'm trying to scroll top after an HTTP response.

Code

 openPDFVievwer(data) {
  this.obj= JSON.parse(data._body);
  document.getElementById('spinner').style.display = 'none';
  window.scrollTo( 0 , 0);
}
  • when I'm trying to scroll bottom after rendering another component.

Code

searchData(data) {
    this.document = data;
    this.searchResultDiv = true; // where component will be rendered
    window.scrollTo( 0 , document.body.scrollHeight);
  }

but, both seem to be not working.

Is there something that I'm doing wrong?

like image 617
Abhishek Ekaanth Avatar asked Dec 20 '17 10:12

Abhishek Ekaanth


3 Answers

Answer for angular 2+

It's very simple, Just create an any element

e.g. <span id="moveTop"></span> or add just id into the element or use already existed Id where you have to move top, down, mid etc.

and add this method on specific event, like I want to move top when edit as my list list too much.

 gotoTop() {

   var scrollElem= document.querySelector('#moveTop');
   scrollElem.scrollIntoView();  
  }

or If you want to send Id as Parameter you simply just create Optional Parameter

gotoTop(elementId?: string) {

    if (elementId != null) {
        var element = document.querySelector(elementId);
        element.scrollIntoView();
    } 
    else {
        var element = document.querySelector('#moveTop');
        element.scrollIntoView();
    }
}
like image 106
Deva Avatar answered Nov 17 '22 22:11

Deva


try into html

<div #list [scrollTop]="list.scrollHeight"></div>

Solution 2

In Component define id into html id="scrollId"

const element = document.querySelector('#scrollId');
element.scrollIntoView();
like image 31
Shailesh Ladumor Avatar answered Nov 17 '22 21:11

Shailesh Ladumor


Above solution wasn't working for me, Try this code:

import { Router, NavigationEnd } from '@angular/router';
constructor(private router: Router)
ngOnInit()
   {
     this.router.events.subscribe((evt) => {
    if (!(evt instanceof NavigationEnd)) {
    return;
      }
  document.getElementsByTagName("app-website-nav")[0].scrollIntoView();
});
   }
like image 29
aravind balaji Avatar answered Nov 17 '22 20:11

aravind balaji