Search code examples
angularscrolltop

scrollTop not working after adding ngAfterViewChecked


I need to add MovetoTop and MovetoBottom buttons.

Also I need automatically MovetoBottom when the page is loading.

Code is not working.(Only scrollToBottom function works, scrollToTop function does not works) after calling the scrollToBottom function ngAfterViewChecked.

Please help

Here I am sharing my code.

Typescript

import { Component, OnInit, ViewChild, ElementRef, AfterViewChecked } from '@angular/core';
import { Router  } from '@angular/router';

@Component({
  selector: 'app-review',
  templateUrl: './review.component.html',
  styleUrls: ['./review.component.scss']
})
export class ReviewComponent implements OnInit  {
  @ViewChild('scrollMe', { read: ElementRef }) public scroll: ElementRef;




  ngAfterViewChecked() {        
     this.scrollToBottom();        
  }

  public scrollToBottom() {
    console.log(this.scroll.nativeElement.scrollTop);
    this.scroll.nativeElement.scrollTop = this.scroll.nativeElement.scrollHeight;

  }

  public scrollToTop() {
    this.scroll.nativeElement.scrollTop = 0;
  }


}

HTML

<div #scrollMe style="overflow: scroll; overflow-x: hidden;height:100%;">
 Hai
</div>

Solution

  • Try this in scrollToTop() function..

    public scrollToTop() {
      this.scroll.nativeElement.scrollTop(0);
    }