打字稿错误:@viewChild undefined

时间:2017-07-18 07:01:49

标签: angular typescript ionic2 ionic3

尝试使用Ionic Tabs文档中tabs.ts中的select()方法。但似乎当我尝试运行它时,它说“select is undefined”,当我尝试console.log(tabs)时,我发现我的viewChild实际上是空的/未定义的。尝试搜索viewChild未定义但无法理解原因的原因。

离子标签文档链接: https://ionicframework.com/docs/api/components/tabs/Tabs/

tabs.html

<ion-tabs #tabs>
  <ion-tab [root]="tab1Root" tabTitle="Request" tabIcon="alert"></ion-tab>
  <ion-tab [root]="tab2Root" [rootParams]="detailParam" tabTitle="Pending" 
   tabIcon="repeat"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="Completed" tabIcon="done-all"></ion-
   tab>
  <ion-tab [root]="tab4Root" tabTitle="Profile" tabIcon="person"></ion-tab>  
</ion-tabs>

tabs.ts

import { Component, ViewChild } from '@angular/core';
import { NavController, NavParams, AlertController, Tabs } from 'ionic-
angular';
import { PendingJobPage } from '../pending-job/pending-job';
import { CompletedJobPage } from '../completed-job/completed-job';
import { RequestPage } from '../request/request';
import { ProfilePage } from '../profile/profile';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {

  @ViewChild('tabs') tabRef: Tabs;
  pending: any;
  apply: boolean;
  detailsParam: any;

  tab1Root = RequestPage;
  tab2Root = PendingJobPage;
  tab3Root = CompletedJobPage;
  tab4Root = ProfilePage;

  constructor(public navParams: NavParams, public navCtrl: NavController) {
    this.pending = this.navParams.get('param1');
    this.apply = this.navParams.get('apply');
    this.detailsParam = this.navParams.data;
    console.log("a = ", this.tabRef);

    if(this.apply === true){
      this.navCtrl.parent.select(1);
    }
    else{
      this.navCtrl.parent.select(0);
    }
  }
}

1 个答案:

答案 0 :(得分:4)

就像你在Angular Docs中看到的那样,

  

ViewChild在视图初始化后设置

  

ViewChild在检查视图后更新

export class AfterViewComponent implements  AfterViewChecked, AfterViewInit {

  ngAfterViewInit() {
    // viewChild is set after the view has been initialized <- Here!
  }

  ngAfterViewChecked() {
    // viewChild is updated after the view has been checked <- Here!
  }

  // ...

}

因此,代码的问题是在执行构造函数时尚未初始化视图。您需要将与ngAfterViewInit生命周期钩子中的选项卡交互的所有代码放在:

  ngAfterViewInit() {
    // Now you can use the tabs reference
    console.log("a = ", this.tabRef);
  }

如果您只想使用Ionic自定义生命周期事件,则需要使用ionViewDidEnter钩子:

export class TabsPage {

@ViewChild('myTabs') tabRef: Tabs;

ionViewDidEnter() {
    // Now you can use the tabs reference
    console.log("a = ", this.tabRef);
 }

}
相关问题