Ionic Scroll Bottom ?*

I am using ngAfterViewChecked(). Mine code structure is -

home.html -

<ion-content padding>
    <div #scrollMe id="messages-container" style="overflow: auto; height: 100%;">
        // All messages elemets. Scroll
    </div>
</ion-content>

home.ts -

import { Component,ViewChild, AfterViewChecked, * * } from '@angular/core';
.
.
export class HomePage implements OnInit, AfterViewChecked{
    // used for scrolling the pane
    @ViewChild('scrollMe') private myScrollContainer: ElementRef;

    ngAfterViewChecked() {
        this.scrollToBottom();
    }

    scrollToBottom(): void {
        // method used to enable scrolling
        this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
    }
}

Bonus - In case you have “Load More messages” button for chat app, within scrollToBottom(), you can write conditions to calculate previous height of container. But keep that variable global.

OR -

home.html -

<ion-content #scrollMe padding style="overflow: auto; height: 100%;">
    <div id="messages-container">
        // All messages elemets. Scroll
    </div>
</ion-content>

home.ts -

import { Component,ViewChild, AfterViewChecked, * * } from '@angular/core';
.
.
export class HomePage implements OnInit, AfterViewChecked{
    // used for scrolling the pane
    @ViewChild('scrollMe') private myScrollContainer: ElementRef;

    ngAfterViewChecked() {
        this.scrollToBottom();
    }

    scrollToBottom(): void {
        // methods used to enable scrolling
        var elemObj:any = this.myScrollContainer;
        if(this.clickedLoadMore.clicked && this.clickedLoadMore.data_added){
          // If load more was clicked and data is available
          elemObj.scrollTo(0, elemObj.getContentDimensions().scrollHeight - this.oldChatHeight, 0);
          this.updatePreviousMessagesSize();
        }
        else if(this.messages.length > this.previousMessagesSize){
          // If new message has came in messages array
          elemObj.scrollToBottom();
          this.updatePreviousMessagesSize();
        }
    }
}

I have included my codes where I am comparing my previous message height with the new one to maintain current view when new messages loads after clicking on Load More button.

I have calculated this.oldChatHeight in other part of overall code which is -

this.oldChatHeight = elemObj.getContentDimensions().scrollHeight;

Notice I have used ElementRef in @ViewChild('scrollMe') private myScrollContainer: ElementRef instead of Content which is an alternate of the way mentioned in Ionic document

3 Likes