Ionic 4 ion-content scroll to bottom
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';
- In constructor add
public _zone: NgZone
- 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);
}
tyn
I code in Java & PHP most of the time & currently learning TensorFlow & Keras. Coder's block sucks and that's why I'm here.
Updated on June 01, 2021Comments
-
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
fromionic-angular
instead ofIonContent
from@ionic/angular
. I cannot seem to use Content in Ionic 4 as it doesn't have the scrollToBottom method. -
Tomas Vancoillie about 5 yearsSo your implementation was correct. The IonContent import isn't necessary, you can get the content ID without the IonContent import.
-
tyn about 5 yearsI've changed my code from importing IonContent to the content ID. At first it doesn't work, however I tried to call
this.scrollToBottomOnInit()
insideionViewDidEnter()
and it works okay now. I figure it might be caused by callingthis.scrollToBottomOnInit()
before the messages are loaded -
Tomas Vancoillie about 5 yearsGood 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 about 5 yearsAh 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 about 5 yearsjust for note: adding some delays might make it work. for example:
setTimeout(()=>{this.scrollToBottomOnInit();},200);
-
D.Hodges over 4 yearsWhich angular lifecycle hook would you use instead of ionViewDidEnter()?
-
Josh about 4 yearsWorks, confirmed 2020.February
-
ihor.eth almost 4 yearsthis.content might not be available yet in ngOnInit. I think it should be called from ngAfterViewInit lifecycle hook
-
Wesley Gonçalves over 3 yearsThis
setTimeout
fixed a timing issue. I was adding an element to theion-content
and then scrolling down. But the element was added after the scroll down event. ThesetTimeout
fixed it. -
B Snow about 3 yearsThis was the best solution for me. Worked perfectly Thank you!
-
Ifeanyi Amadi about 3 yearsThanks, B Snow.