簡體   English   中英

Ionic 4 離子含量滾動到底部

[英]Ionic 4 ion-content scroll to bottom

我正在使用 Ionic 4 創建一個聊天頁面,我試圖讓它自動滾動到頁面底部。 我是這樣做的,但它不起作用:

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);
    }
}

在 html 文件中:

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

顯示的錯誤是:

ng:///ChatroomPageModule/ChatroomPage_Host.ngfactory.js:5 錯誤類型錯誤:無法讀取未定義的屬性“scrollToBottom”

請賜教我做錯了什么。 我發現的大多數教程都使用 Ionic 3,它們使用來自ionic-angular Content而不是來自@ionic/angularIonContent 我似乎無法在 Ionic 4 中使用 Content,因為它沒有 scrollToBottom 方法。

您可以使用方法scrollToBottom()到達內容的底部

scrollToBottom(duration?: number) => Promise<void>

ion-content添加 ID

<ion-content #content>
</ion-content>

獲取 .ts 中的內容 ID 並使用選定的持續時間調用 scrollToBottom 方法

@ViewChild('content') private content: any;

ngOnInit() {
  this.scrollToBottomOnInit();
}

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

https://ionicframework.com/docs/api/content

編輯:

ViewChild 使用提供的內容 ID 獲取正確的數據

@ViewChild('content') private content: any;

ngOnInit 與 ionViewDidEnter / ionViewWillEnter

如果您從導航堆棧返回,則 ngOnInit 不會觸發, ionViewWillEnter / ionViewDidEnter 會。 因此,如果您將函數放在 ngOnInit 中,如果您向后導航,則 scrollToBottom 將不起作用。

由於最近對 ionic 4 的更改,我發現建議答案中的代碼不再適合我。 希望這對所有新人都有幫助。

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);

  }
}

在 .html 文件中沒有為 < ion-content > 指定 id

官方文檔是指ion-content 發布本文時使用的離子版本如下所示。

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

你的大部分代碼都很好。 您只需要在 Ionic 4 中進行 2 處更改,這應該對您有用。以下是更改:

更改 1(HTML 文件):

代替:

<ion-content padding id="content">

和:

<ion-content padding #content>

更改 2(TS 文件):

代替:

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

和:

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

筆記:

如果您不導入IonContent (類似於您已經這樣做的方式),代碼將無法編譯,您將看到如下控制台錯誤:

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

其中MessagesPageModule是與您嘗試在其中實現該功能的頁面關聯的模塊。

Tomas Vancoillie 是對的,但是當您添加新文本並添加到列表時,它不會將其推到輸入文本上方。 因此,要將文本推送到數組並將視圖更新到底部,請再次使用 ngZone。

1.

import { Component, ViewChild,NgZone } from '@angular/core';
  1. 在構造函數中添加
public _zone: NgZone
  1. 調用你的函數
this._zone.run(() => {
  setTimeout(() => {
    this.contentchat.scrollToBottom(300);
  });
}); 

這在201912 月對我有用

.html

<ion-content #content>

</ion-content>

.ts

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

constructor(){}

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


 scrollToBottom(): void {
    this.content.scrollToBottom(300);
  }

這最終對我有用。 你可以試試看。

.ts

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

/.. 類聲明 .../

@ViewChild('content') content : IonContent;

constructor(public _zone: NgZone){
}

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

scrollToBottom()
{
    this._zone.run(() => {

      const duration : number = 300;

      setTimeout(() => {
        
        this.content.scrollToBottom(duration).then(()=>{

          setTimeout(()=>{

            this.content.getScrollElement().then((element:any)=>{

              if (element.scrollTopMax != element.scrollTop)
              {
                // trigger scroll again.
                this.content.scrollToBottom(duration).then(()=>{

                  // loaded... do something

                });
              }
              else
              {
                // loaded... do something
              }
            });
          });
        });

      },20);
    }); 
}
@ViewChild(IonContent) content: IonContent;
scrollToBottom() {
    setTimeout(() => {
      if (this.content.scrollToBottom) {
        this.content.scrollToBottom();
      }
    }, 400);
  }

在函數中的任何地方使用:

this.scrollToBottom();

一個 mi me funcionó con la implementationacion de AfterViewChecked del ciclo de vida de angular en angular 9 con fecha al 30/10/2020

  1. 進口商

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

    import { IonContent } from '@ionic/angular';

  2. 執行者 AfterViewChecked

    export class PublicationsProductPage implements AfterViewChecked {

  3. Crear el metodo scrollToBottom

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

  4. Llamar el metodo scrollToBottom desde la implementationación de AfterViewChecked

    ngAfterViewChecked(){ this.scrollToBottom(); }

con este codigo te aseguras de que siempre se dirija al final del ionconten

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM