Angular 2+ Bottom to Top Scroll with or without behavior

0
772

Try into html

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

In Component define id into html id="scrollId"

const element = document.querySelector('#scrollId');
element.scrollIntoView();

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

From MDN documentation of scrollIntoView You can pass in option instead of boolean.

scrollIntoViewOptions Optional
A Boolean or an object with the following options:
{
  behavior: "auto"  | "instant" | "smooth",
  block:    "start" | "center" | "end" | "nearest",
  inline:    "start" | "center" | "end" | "nearest",
}

So you can simply pass parameter like this.

scrollToQuestionNode(id) {
  const element = document.getElementById(id);
  element.scrollIntoView({ block: 'end',  behavior: 'smooth' });
}

Reference: https://developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView

LEAVE A REPLY

Please enter your comment!
Please enter your name here