Is there a way to scroll to the bottom of the page in angular when clicking a button?

Viewed 7321

I am working on an angular project and I need to figure out a way to automatically scroll to the bottom of the page when the user clicks a button.

I tried doing this with the jQuery function animate() which didn't work for me. I have also tried the below function:

scrollToBottom() {
  let myElement = document.getElementById("myPageId");
  myElement.scrollTop = myElement.scrollHeight;
}

This function only works when I call it from my html page, while I need to use it in my ts file when the user clicks a button.

3 Answers

create a button which executes this normal JavaScript as written by @chestas and also available here

relevant TS:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  goToBottom(){
    window.scrollTo(0,document.body.scrollHeight);
  }
}

relevant HTML:

<button type="button" (click)="goToBottom()">go to bottom </button>

complete stackblitz

I needed to scroll to the bottom of the page on load, but it didn't work since I am loading a lot of data from API. What worked for me is putting it inside setTimeout function to render the page first and then to scroll down.

ngOnInit() {
    this.scrollToButtom();
  }

scrollToButtom() {
    setTimeout(() => {
      window.scrollTo(0, document.body.scrollHeight);
    }, 500);
}
Related