【问题标题】:Ionic 2 : How do you reinstantiate @ViewChild if you dismiss the view?Ionic 2:如果您关闭视图,您如何重新实例化@ViewChild?
【发布时间】:2017-09-16 14:09:27
【问题描述】:

我正在创建一个聊天体验,并且页面通过使用 ionic-angular 上的 Content 中的 scrollToBottom 方法来跟上对话。如果我从“PreChat.html”开始并转到“Chat.html”然后我关闭“Chat.html”以返回“PreChat.html”并再次返回“Chat.html”我收到以下错误: “无法读取 null 的属性‘scrollToBottom’”。体验应该可以随时或重复进入。

PreChat.html:

<ion-content>
  <button (click)="goToChat()" href="#">
    Chat
  </button>
</ion-content>

PreChat.ts:

import { Component } from '@angular/core';
import { ModalController } from 'ionic-angular';
import { Chat } from '../chat';

@Component({
  selector: 'preChat',
  templateUrl: 'preChat.html'
})
export class PreChat  {
   constructor(private modalCtrl: ModalController){}

   goToChat(): any {
    let profileModal = this.modalCtrl.create(Chat);
    profileModal.present();
  }
}

聊天.html:

<ion-content>
  <button ion-button="filter-button"(click)="dismiss()">
    <ion-icon name="close"></ion-icon>
  </button>
  <div *ngFor="let convo of conversationArray">
    <div class="b-text">{{convo.speak}}</div>
  </div>
</ion-content>

聊天.ts:

import { Component, ViewChild } from '@angular/core';
import { Content, Events, ViewController } from 'ionic-angular';

@Component({
  templateUrl: 'Chat.html'
})

export class Chat {
  @ViewChild(Content) content: Content;
  conversationArray: any[] = [];
  constructor(private events: Events, private viewCtrl: ViewController){
    this.events.subscribe('conversation', convo => {
      this.conversationArray = convo;
      this.content.scrollToBottom();
    })
  }
  dismiss() {
   this.viewCtrl.dismiss(); 
 }
}

【问题讨论】:

  • html中是否提供了名为'content'的id?它需要使用#content 引用,然后您可以尝试this.content.nativeElement.scrollToBottom(),因为它是您所指的本机元素。有关更多详细信息,请查看:stackoverflow.com/questions/39158922/…
  • @Deepak,当内容专门引用 时,为什么我需要 id? ionicframework.com/docs/api/components/content/Content
  • 经过大量搜索后,似乎有一种方法可以使用 ViewChild 在组件之间传递数据,但这并不完全适用于使用离子/角度内容的上下文。话虽如此,我的目的是创建一个基于聊天的底部滚动,如 Ionic 文档中所示。这就是编写大量代码的方式,除了错误和不一致。此链接提供了一个更清晰的解决方案:plnkr.co/edit/…

标签: javascript angular ionic2 angular2-template


【解决方案1】:

为此,您必须使用ionViewDidEnter 页面事件而不是constructor

当页面完全进入并且现在是活动页面时运行。这 无论是第一次加载还是缓存页面,都会触发事件。

ionViewDidEnter() : void {
 this.platform.ready().then(() => { //platform ready
   this.events.subscribe('conversation', convo => {
      this.conversationArray = convo;
      this.content.scrollToBottom();
    })
 })
}

【讨论】:

  • 感谢您的建议,但没有奏效。使用 ionViewDidEnter 时是否遗漏了一个步骤或细节?我对这个生命周期钩子并不特别熟悉。可能与 Chat.ts 和 Chat.html 作为模态有关吗?
  • 嗯...这是关于生命周期钩子的文档:github.com/driftyco/ionic/blob/master/src/navigation/…
  • 我认为这个问题与@ViewChild 有关。它需要重新实例化,但现在还没有发生。对这种细微差别有什么想法吗?
  • content 上进行调试时会显示什么?
  • 如何对内容进行调试?就目前而言,我的内容为空。
【解决方案2】:

请尝试以下方法:

this.content = this.ViewCtrl.getContent();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2012-11-04
    • 2011-01-08
    • 2018-04-15
    • 1970-01-01
    相关资源
    最近更新 更多