0

So I tried making a chatbox window component that displays all the messages. After I load and display the messages I want to scroll down in the window so the user can see the latest messages.

Before I did this with ngAfterViewChecked and the method scrollToBottom()

@ViewChild('window') window;

ngAfterViewChecked() {
    this.scrollToBottom();
  }

scrollToBottom() {
    console.log('reached scrollToBottom');
    try {
      console.log(this.window.nativeElement.scrollTop);
      console.log(this.window.nativeElement.scrollHeight);
      this.window.nativeElement.scrollTop = this.window.nativeElement.scrollHeight;
      console.log(this.window.nativeElement.scrollTop);
    } catch (err) {}
  }

As you can see I did three console.logs. The first one returns 0, the second one return 320 and when I check whether the scrolltop has been changed to the scrollHeight it says that the scrollTop still is 0.

Does someone know what's causing this?

enter image description here

tilly
  • 2,229
  • 9
  • 34
  • 64
  • 1
    MDN states that "...element can't be scrolled when e.g. it has no ``overflow`` - how about your chatbox window? – Buczkowski Oct 20 '18 at 16:29
  • Is `scrollHeight` larger than `offsetHeight` or `clientHeight`? – ConnorsFan Oct 20 '18 at 16:56
  • 1
    The message are probably not loaded yet when you try to scroll. Try using `ViewChildren` and processing the `QueryList.changes` event, as suggested in [this answer](https://stackoverflow.com/a/50215342/1009922) (you can scroll or set the focus, whichever works best in your case). – ConnorsFan Oct 20 '18 at 17:26

4 Answers4

0

The Element.scrollHeight read-only property is a measurement of the height of an element's content, including content not visible on the screen due to overflow.

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

You should try this, as I had used once in my code

const s: any = document.getElementsByClassName('someClassName')[0];
const height = s.scrollHeight + 'px';
s.style.setProperty('height', height.toString(), 'important');}, 500);
Vivek Kumar
  • 4,822
  • 8
  • 51
  • 85
0

Use top property

this.window.nativeElement.style.top = this.window.nativeElement.scrollHeight;

or

this.window.nativeElement.top = this.window.nativeElement.scrollHeight;
Sunil Singh
  • 11,001
  • 2
  • 27
  • 48
  • I tried it and the top element gets changed to the scrollHeight, but it still doesn't scroll down – tilly Oct 20 '18 at 17:19
0

In some Angular's way, set the CSS overflow Property to scroll for the nativeElement.

Something like

.native-element {
    overflow: scroll;
}
-1

I think you might find helpful this scrollIntoView function which is called on an element to scroll it to make it visible: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

Svilen
  • 44
  • 5