ionic 2 + angular 2 : auto scroll to bottom of list / page / chat

后端 未结 9 1486
误落风尘
误落风尘 2021-02-13 12:42

I\'m trying to code a page with two segments \"chat\" and \"content\". I want that one \"chat\" segment the page auto-scroll to the bottom with no effect. The chat is a &l

9条回答
  •  悲&欢浪女
    2021-02-13 13:10

    First off all, @rinukkusu answer is right but it doesn't work on my case because (parent of ) has some bugs with it (ionic developers are working on that), so I had to put that element with scroll:hidden and create a second content inside to apply the auto-scroll. Finally with the right (s)css I called the function on construtor when the page loads and then each time the users clicks on "chat" segment.

    chat.html

    
    
        
            
                Chat
            
            
                Profile
            
        
    
    
    
    
    
    
    
        
        
    (... make sure the content is bigger than the container to see the auto scroll effect ...)
    (... content of profile segment ...)

    chat.js

    constructor () {
    
        // when the user opens the page, it shows the "chat" segment as initial value
        this.segment = 'chat'; 
    
        // when page loads, it calls autoScroll();
        if (this.segment == 'chat') {
            console.log('chat');
            this.autoScroll();
        };
    }
    
    /*Here comes the tricky. 
     If you don't use setTimeout, the console will say that
     #chat-autoscroll doesn't exist in the first call (inside constructor). 
     This happens because the script runs before the DOM is ready. 
     I did a workaround with a timeOut of 10ms.
     It's enough time to DOM loads and then autoScroll() works fine.
    */
    autoScroll() {
        setTimeout(function () {
            var itemList = document.getElementById("chat-autoscroll");
            itemList.scrollTop = itemList.scrollHeight;
        }, 10);
    }
    

    Conclusion: The function is called twice. When the page is loaded (constructor) and each time the user comes back to "chat" segment. (click)="autoScroll()"

    I hope this helps someone. If you know better way, let me know! I started playing with Angular2 and Ionic2 a couple of weeks ago so there is a lot of concepts/bases that I might be missing here.

    Thanks :)

提交回复
热议问题