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

后端 未结 9 1507
误落风尘
误落风尘 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 12:56

    Another solution is to "observe" changes in the scroll view and scroll automatically. i.e. if there are new HTML elements where the messages appear then scroll to the bottom.

    export class MessagesPage implements OnInit, OnDestroy {
      autoScroller: MutationObserver;
    
      ngOnInit() {
        this.autoScroller = this.autoScroll();
      }
    
      ngOnDestroy() {
        this.autoScroller.disconnect();
      }
    
      autoScroll(): MutationObserver {
        const autoScroller = new MutationObserver(this.scrollDown.bind(this));
    
        autoScroller.observe(this.messagesList, {
          childList: true,
          subtree: true
        });
    
        return autoScroller;
      }
    
      scrollDown(): void {
        this.scroller.scrollTop = this.scroller.scrollHeight;
        this.messageEditor.focus();
      }
    
      private get messageEditor(): HTMLInputElement {
        return document.querySelector('ion-input');
      }
    
      private get messagesList(): Element {
        return document.querySelector('.messages');
      }
    
      private get scroller(): Element {
        return this.messagesList.querySelector('.scroll-content');
      }
    }
    

    Template:

    
      
        
          

    (take from Ionic2CLI-Meteor-WhatsApp on Github)

提交回复
热议问题