Ionic 4 ion-content scroll to bottom Ionic 4 ion-content scroll to bottom typescript typescript

Ionic 4 ion-content scroll to bottom


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.


Due to recent changes on ionic 4, I found the code in suggested answer no longer works for me. Hope this helps all the new comers.

import { IonContent } from '@ionic/angular';export class IonicPage implements OnInit {@ViewChild(IonContent, {read: IonContent, static: false}) myContent: IonContent;  constructor() {}  ScrollToBottom(){    setTimeout(() => {      this.myContent.scrollToBottom(300);   }, 1000);  }}

No id specified in .html file for < ion-content >

Official documentation refers to ion-content.Ionic version used listed below at the time of this post.

Ionic CLI                     : 5.4.13Ionic Framework               : @ionic/angular 4.11.3@angular/cli                  : 8.1.3


Most of your code is fine. You just need to do 2 changes and that should work for you, in Ionic 4. Here are the changes:

Change 1 (HTML FILE):

Replace:

<ion-content padding id="content">

with:

<ion-content padding #content>

Change 2 (TS FILE):

Replace:

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

with:

scrollToBottomOnInit() {    setTimeout(() => {        if (this.content.scrollToBottom) {            this.content.scrollToBottom(400);        }    }, 500);}

NOTE:

If you do not import IonContent (similar to the way you already did), the code will fail to compile and you will see console errors such as this:

ERROR Error: Uncaught (in promise): ReferenceError: Cannot access 'MessagesPageModule' before initialization

where MessagesPageModule is the Module associated with the page that you are trying to implement the feature in.