javascript - ionic 2 + Angular 2 : auto scroll to bottom of list/page/chat

标签 javascript angular chat ionic2 autoscroll

我正在尝试编写包含“聊天”和“内容”两个部分的页面。我希望那个“聊天”将页面自动滚动到底部而没有任何效果。聊天是<ion-list>有几个<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>

我使用的是 Javascript,而不是 typescript,而且我不想不使用 jQuery。 谢谢 :) 另外,当我转到“内容”部分并返回“聊天”时,我想再次自动滚动聊天。

最佳答案

这是我的做法:

chatPage.html

<ion-content #content padding class="chatPage">

  <ion-list no-lines>
    <ion-item *ngFor="let msg of messages" >
      <chat-bubble [message]="msg"></chat-bubble>
    </ion-item>
  </ion-list>

</ion-content>

chatPage.html 中重要的一点是 #content<ion-content> .我将使用 #content标识符以获取对 <ion-content> 的引用在我的 chatPage.js 中使用 ViewChild .

现在是实际的滚动逻辑:

chatPage.js

import {Component, ViewChild} from '@angular/core';

@Component({
  templateUrl: 'build/pages/chatPage/chatPage.html',
  queries: {
    content: new ViewChild('content')
  }
})
export class ChatPage {
  constructor() { 

  }

  //scrolls to bottom whenever the page has loaded
  ionViewDidEnter(){
    this.content.scrollToBottom(300);//300ms animation speed
  }
}

此外,每当我的 chatPage 需要在列表中显示另一条聊天消息(收到新消息或发送新消息)时,我使用以下代码滚动到新底部:

setTimeout(() => {
  this.content.scrollToBottom(300);//300ms animation speed
});

Typescript 更新

当我给出这个答案时,我正在使用 Ionic 2 项目的 JavaScript 版本。随着时间的推移,我切换到 TypeScript,但我忘记更新答案,因此,这里有一个针对 chatPage.js(ts) 的小更新:

chatPage.ts

import {Component, ViewChild} from '@angular/core';

@Component({
  templateUrl: 'chatPage.html'
})
export class ChatPage {
  @ViewChild('content') content:any;

  constructor() { }

  //scrolls to bottom whenever the page has loaded
  ionViewDidEnter(){
    this.content.scrollToBottom(300);//300ms animation speed
  }
}

关于javascript - ionic 2 + Angular 2 : auto scroll to bottom of list/page/chat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37415085/

相关文章:

页面加载时 Angular valuechanges 调用多次

java - 使用 Java 的视频/语音聊天 Web 应用程序

javascript - jQuery 突出显示滚动上的导航链接不起作用

javascript - 如何在不使用 Active X 的情况下将 DDE 与 Javascript 结合使用?

PHP读取Javascript数组

html - angular 2 - primeng 有一个单独的行用于过滤器而不是内部标题

javascript - 每个 session 仅 jQuery getJSON 一次

Angular :如何循环数字?

ios - 编译错误 : Header 'ChattoAdditions-Swift.h' not found

android - 将 WhatsAPI/Yowsup 集成到 Android 中