2

Live example: https://angular-txvcna.stackblitz.io/ (Code).

I have a "chat" component and I want to get the div to scroll to the bottom each time a message is added.

I'm adding a new message by pushing an item to an array (this.messages.push(message)), and trying to scroll to the bottom right after that. It seems like the scrolling operation this.chatboxBody.nativeElement.scrollTop = this.chatboxBody.nativeElement.scrollHeight; is before the lifecycle hooks of angular, because scrollHeight has the older value of the height as it excutes.

At the moment I use setTimeout to fix it, but it really feels like a shortcut. How can I fix that? (Ideally - to somehow subscribe to the hook that updates the child component)

noamyg
  • 2,747
  • 1
  • 23
  • 44

1 Answers1

1

I have a couple of ideas:

  1. You could change the messages input to a setter, such that when the message is input it sets a private version of the message and handles the scrolling within the component. (Personally it seems to me that this is the best solution as the logic of how to scroll to the bottom would then not have to be repeated in each place that this component is used)
    private _message: VivrMessage;
        @Input()
            set message(val: VivrMessage){
        if (val){
            this._message = val;
            this.handleScrolling();
        }
    }
  1. You could do similar to the above, but instead of handling the scrolling in the messages component, have an output that would then have the parent component do the work.
dmoore1181
  • 1,793
  • 1
  • 25
  • 57
  • Method 1 is a little helpful, but I have to use scrollIntoView() and that's not the same as scrolling to the bottom. Plus, that way the scrolling is bound to initialization of `message` (what if I want to change its' content?). Method 2 is really dirty - I'm already using `Input` to set the message, and `Output` to notify when the user clicks on an option - defining another `Output` seems like a real workaround ;-). Thanks for your answer. – noamyg May 21 '19 at 12:10
  • 1
    If you change the content, the same setter will be fired. Each time that the parent changes its value that it has set to the message input, the setter will execute. – dmoore1181 May 21 '19 at 12:36