rashadb
rashadb

Reputation: 2543

Ionic 2 : How do you reinstantiate @ViewChild if you dismiss the view?

I'm creating a chat experience and the page keeps up with the conversation by using the scrollToBottom method from Content on ionic-angular. If I start at the "PreChat.html" and go to "Chat.html" then I dismiss "Chat.html" to go back to "PreChat.html" and return again to "Chat.html" I get the following error: "Cannot read property 'scrollToBottom' of null". The experience should be able to be entered into at any time or repeatedly.

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

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

Chat.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(); 
 }
}

Upvotes: 3

Views: 899

Answers (2)

Atmosuwiryo
Atmosuwiryo

Reputation: 114

Please try the following:

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

Upvotes: 1

Sampath
Sampath

Reputation: 65920

You have to use ionViewDidEnter page event instead of the constructor for that.

Runs when the page has fully entered and is now the active page. This event will fire, whether it was the first load or a cached page.

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

Upvotes: 3

Related Questions