Unable to fully scroll down after ngFor is done adding an item and expanding the ScrollView height


#1

Hi guys,

I have a chat component that renders chat bubbles. The bubbles are in the ScrollView. Every time a message comes, i want it to scroll all the way down - just like WhatsApp or Viber, newest message at the bottom of the ScrollView. I was able to do it, but only when entering the page for the first time. Once you add a new message the message is added, but it is not visible since it does not scroll all the way down the newly expanded ScrollView height even though i have code like this below. The rendering is done via ngFor over a messages array that i push new messages onto. So i push a new message, the message is rendered (scrollview is taller now), but the scroll to bottom does not scroll all the way to the bottom even though i called it after I added the new message to the array. Only after i add another message, does the scroll to bottom show the previous, but again not the newest message. I’ve tried a few things, but am running out of ideas. I’d like to be able to to call scrollDown once the ScrollView is fully rendered and the new height is correct. I tried:

  • setTimeout

  • DoCheck

  • etc.

    //interesting read: https://stackoverflow.com/questions/37741179/event-when-view-is-rendered-on-nativescript
    public scrollDown(){//called after messages.push(newmessage) which probably auto renders through ngFor
    var offset = this.scroller.nativeElement.scrollableHeight; // get the current scroll height
    console.log("this.scroller.nativeElement.scrollableHeight: " + offset);

      this.scroller.nativeElement.scrollToVerticalOffset(offset, false); // scroll to the bottom
    

    }

Please help,

Thanks!


#2

Hi there!

This is your alter ego. Here is the solution - I don’t know why it didn’t work for you before, but it does now…

        setTimeout(()=>{
            this.scrollDown();
        }
        , 100);