w.braham
w.braham

Reputation: 53

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

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.

Upvotes: 3

Views: 18371

Answers (5)

Mukul Raghav
Mukul Raghav

Reputation: 489

This code helped me

<div id="focusBtn"></div>

const element = document.getElementById("focusBtn");
element.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });

Upvotes: 1

Prince
Prince

Reputation: 11

<div style='...' #scrollMe [scrollTop]="scrollMe.scrollHeight">
  <p>
    #scrollMe [scrollTop]="scrollMe.scrollHeight //add in your div
  </p>
</div>

Upvotes: 1

DBK
DBK

Reputation: 1

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

Upvotes: 0

chestas
chestas

Reputation: 124

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

Upvotes: 0

Akber Iqbal
Akber Iqbal

Reputation: 15031

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

Upvotes: 6

Related Questions