3

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.

Akber Iqbal
  • 13,723
  • 12
  • 47
  • 62
w.braham
  • 43
  • 2
  • 4
  • Look at this hopefully it will help https://stackoverflow.com/questions/35232731/angular2-scroll-to-bottom-chat-style – Noman Fareed Jun 12 '19 at 11:54

2 Answers2

4

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

Akber Iqbal
  • 13,723
  • 12
  • 47
  • 62
  • 1
    wow.. super clean! Not sure why people are going for ElementRef and ViewChild for scrolling to bottom... This is definitely the solution for a functionality that scrolls the page down to the bottom. – Gel Oct 20 '21 at 20:09
0

look at the answer here Scroll Automatically to the Bottom of the Page here is the code, just add it inside your function scrollToBottom

window.scrollTo(0,document.body.scrollHeight);
chestas
  • 114
  • 1
  • 6
  • You should provide detailed answer not one-liner solution. check https://stackoverflow.com/help/how-to-answer – Abhijeet Jun 12 '19 at 12:56