Ionic 4 ion-content scroll to bottom

29,201

Solution 1

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.

Solution 2

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.13
Ionic Framework               : @ionic/angular 4.11.3
@angular/cli                  : 8.1.3

Solution 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.

Solution 4

Tomas Vancoillie is right, but when you add new text and add to list, it won't push it up above input text. Therefore to push text to array and update view to bottom again use ngZone.

1.

import { Component, ViewChild,NgZone } from '@angular/core';
  1. In constructor add
public _zone: NgZone
  1. Call your function
this._zone.run(() => {
  setTimeout(() => {
    this.contentchat.scrollToBottom(300);
  });
}); 

Solution 5

This works for me on December 2019.

.html

<ion-content #content>

</ion-content>

.ts

@ViewChild('content', { static: false }) content: IonContent;

constructor(){}

 ngOnInit(): void {
    this.scrollToBottom();
  }


 scrollToBottom(): void {
    this.content.scrollToBottom(300);
  }
Share:
29,201
tyn
Author by

tyn

I code in Java &amp; PHP most of the time &amp; currently learning TensorFlow &amp; Keras. Coder's block sucks and that's why I'm here.

Updated on June 01, 2021

Comments

  • tyn
    tyn almost 3 years

    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.

  • Tomas Vancoillie
    Tomas Vancoillie about 5 years
    So your implementation was correct. The IonContent import isn't necessary, you can get the content ID without the IonContent import.
  • tyn
    tyn about 5 years
    I've changed my code from importing IonContent to the content ID. At first it doesn't work, however I tried to call this.scrollToBottomOnInit() inside ionViewDidEnter() and it works okay now. I figure it might be caused by calling this.scrollToBottomOnInit() before the messages are loaded
  • Tomas Vancoillie
    Tomas Vancoillie about 5 years
    Good call. ngOnInit doesn't trigger if you come back from a navigation stack, ionViewWillEnter / ionViewDidEnter will. Maybe you could also call the scrollToBottom method after you subscribe to the received data. So when your data comes in, the scrollToBottom is activated. Haven't tried it, just a suggestion to try ;)
  • tyn
    tyn about 5 years
    Ah yes, I should use it for the subscribed data as well. Thanks for the reminder. I think you can edit your answer, I'll accept it. :D
  • tyn
    tyn about 5 years
    just for note: adding some delays might make it work. for example: setTimeout(()=>{this.scrollToBottomOnInit();},200);
  • D.Hodges
    D.Hodges over 4 years
    Which angular lifecycle hook would you use instead of ionViewDidEnter()?
  • Josh
    Josh about 4 years
    Works, confirmed 2020.February
  • ihor.eth
    ihor.eth almost 4 years
    this.content might not be available yet in ngOnInit. I think it should be called from ngAfterViewInit lifecycle hook
  • Wesley Gonçalves
    Wesley Gonçalves over 3 years
    This setTimeout fixed a timing issue. I was adding an element to the ion-content and then scrolling down. But the element was added after the scroll down event. The setTimeout fixed it.
  • B Snow
    B Snow about 3 years
    This was the best solution for me. Worked perfectly Thank you!
  • Ifeanyi Amadi
    Ifeanyi Amadi about 3 years
    Thanks, B Snow.