Ionic 4 ion-content scroll to bottom

tyn picture tyn · Mar 12, 2019 · Viewed 19k times · Source

I am creating a chat page using Ionic 4 and I'm trying to make it automatically scroll to the bottom of the page. I did it like this and it's not working:

import { IonContent } from "@ionic/angular";

export class ChatroomPage implements OnInit {
    messageForm: FormGroup;
    messages: any[];
    messenger: any;
    @ViewChild(IonContent) content: IonContent;

    constructor(
        private navExtras: NavExtrasService,
        private api: RestApiService,
        private httpNative: HTTP
    ) { }

    ngOnInit() {
        this.content.scrollToBottom(300);
    }
}

In the html file:

<ion-header>
    <ion-toolbar color="primary">
        <ion-title>Chatroom</ion-title>
            </ion-toolbar>
        </ion-header>

        <!-- display previous message -->
        <ion-content padding id="content"> 

        <ion-list>
            <ion-item *ngFor="let message of messages">
                {{ message.message }}
            </ion-item>
        </ion-list>

        </ion-content>

    <!-- chat message input -->
    <ion-footer>
        <form [formGroup]="messageForm" (submit)="sendMessage()" (keydown.enter)="sendMessage()">
            <ion-input formControlName="message" type="text" placeholder="Enter your message"></ion-input>
            <ion-button type="submit">Send</ion-button>
        </form>
    </ion-footer>

The error displayed is:

ng:///ChatroomPageModule/ChatroomPage_Host.ngfactory.js:5 ERROR TypeError: Cannot read property 'scrollToBottom' of undefined

Please enlighten me what did I do wrong. Most tutorials I found are using Ionic 3 and they use Content from ionic-angular instead of IonContent from @ionic/angular. I cannot seem to use Content in Ionic 4 as it doesn't have the scrollToBottom method.

Answer

Tomas Vancoillie picture Tomas Vancoillie · Mar 12, 2019

You can reach the bottom of the content with the method scrollToBottom()

scrollToBottom(duration?: number) => Promise<void>

Add an ID to the ion-content

<ion-content #content>
</ion-content>

Get the content ID in .ts and call the scrollToBottom method with a chosen duration

@ViewChild('content') private content: any;

ngOnInit() {
  this.scrollToBottomOnInit();
}

scrollToBottomOnInit() {
  this.content.scrollToBottom(300);
}

https://ionicframework.com/docs/api/content

EDIT:

ViewChild gets the correct data with the provided content ID

@ViewChild('content') private content: any;

ngOnInit vs ionViewDidEnter / ionViewWillEnter

ngOnInit doesn't trigger if you come back from a navigation stack, ionViewWillEnter / ionViewDidEnter will. So if you place the function in ngOnInit, the scrollToBottom won't work if you navigate back.