Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Button Scroll to Top

I developed an image gallery. Is there a way when scrolling on the page, a button would appear to me that when clicking on it all the scroll made was to the top (beginning of the page)?

I already tested some cases that I found and so far none worked :( can someone help me?

BLITZ

code

  <ul class="mdc-image-list my-image-list" style="padding-left: 10px;padding-right: 10px;">
    <li class="mdc-image-list__item" *ngFor="let product of Images; let  j = index;">
      <div class="mdc-image-list__image-aspect-container">
          <img [src]="product.image" class="mdc-image-list__image">
      </div>
    </li>
  </ul>
like image 670
Harry Avatar asked Dec 14 '25 04:12

Harry


1 Answers

Use hostListener to listen window scroll event,Then Use angular ViewPortScroller service, which provide scrollToPostion method use that to scroll to specified position.

Try this:

component.ts

@HostListener('window:scroll', ['$event']) onScroll(event){
    this.pageYoffset = window.pageYOffset;
 }

constructor(private scroll: ViewportScroller) { }

scrollToTop(){
    this.scroll.scrollToPosition([0,0]);
}

Working Example

like image 161
Chellappan வ Avatar answered Dec 16 '25 20:12

Chellappan வ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!