Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to scroll the list to top on button click in angular?

could you please tell me how to scroll the list to top on button click in angular ? I tried like this

 scrollToTop(el){
    el.scrollIntoView();
  }

  <button (click)="scrollToTop(target)">scroll to top</button>

It scroll the list to top .but it hide my addressbar and then user not able see header I think it is not a good solution .anybody have any other good solution

here is my code https://stackblitz.com/edit/angular-f9qxqh?file=src%2Fapp%2Fapp.component.html

like image 471
naveen Avatar asked Dec 14 '22 15:12

naveen


1 Answers

You can scroll to the top of the list by setting the scrollTop property of the container to zero. See this stackblitz for a demo.

<div #container class="container">
  <ul>
    <li *ngFor="let i of items">{{i}}</li>
  </ul>
</div>

<button (click)="container.scrollTop = 0">scroll to top</button>

Here is a simple method that scrolls smoothly to the top of the list. It is based on this answer by bryan60, and adapted to RxJS 6. You can try it in this stackblitz.

<button (click)="scrollToTop(container)">scroll to top</button>
import { interval as observableInterval } from "rxjs";
import { takeWhile, scan, tap } from "rxjs/operators";
...

scrollToTop(el) {
  const duration = 600;
  const interval = 5;
  const move = el.scrollTop * interval / duration;
  observableInterval(interval).pipe(
    scan((acc, curr) => acc - move, el.scrollTop),
    tap(position => el.scrollTop = position),
    takeWhile(val => val > 0)).subscribe();
}
like image 180
ConnorsFan Avatar answered Dec 20 '22 18:12

ConnorsFan