I'm trying to code a page with two segments "chat" and "content". I want that one "chat" segment the page auto-scroll to the bottom with no effect. The chat is a <ion-list>
with several <ion-item>
.
<ion-list>
<ion-item> item 1 </ion-item>
<ion-item> item 2 </ion-item>
....
<ion-item> item 20 </ion-item>
<ion-item> item 21 </ion-item> <!-- user should see directly this item on bottom of the page -->
</ion-list>
I'm using Javascript, not typescript, and I don't wan't to use jQuery. Thanks :) Plus, when I go to "content" segment and go back to "chat" I want to auto-scroll again the chat.
The Ionic has an option to do this and works pretty good: And this is the most appropriate way with angular 2+ and Ionic.
This could help someone, I have given similar answer in Ionic forum. This is implemented in Ionic 3.
I used
ngAfterViewChecked()
to achieve this feature. Following is my code structure -home.html -
home.ts -
.scrollTop
and.scrollHeight
are JavaScript properties, see here.This should work if your
ion-list
element has a fixed height.Another solution is to "observe" changes in the scroll view and scroll automatically. i.e. if there are new HTML elements where the messages appear then scroll to the bottom.
Template:
(take from Ionic2CLI-Meteor-WhatsApp on Github)
I added a check to see if the user tried to scroll up.
First off all, @rinukkusu answer is right but it doesn't work on my case because
<ion-content>
(parent of<ion-list>
) has some bugs with it (ionic developers are working on that), so I had to put that element withscroll:hidden
and create a second content inside to apply the auto-scroll. Finally with the right (s)css I called the function onconstrutor
when the page loads and then each time the users clicks on "chat" segment.chat.html
chat.js
Conclusion: The function is called twice. When the page is loaded (constructor) and each time the user comes back to "chat" segment. (click)="autoScroll()"
I hope this helps someone. If you know better way, let me know! I started playing with Angular2 and Ionic2 a couple of weeks ago so there is a lot of concepts/bases that I might be missing here.
Thanks :)