打字稿错误:@viewChild未定义

Luq*_*har 7 typescript ionic2 ionic3 angular

使用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>
Run Code Online (Sandbox Code Playgroud)

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);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

seb*_*ras 5

就像您在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!
  }

  // ...

}
Run Code Online (Sandbox Code Playgroud)

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

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

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

export class TabsPage {

@ViewChild('myTabs') tabRef: Tabs;

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

}
Run Code Online (Sandbox Code Playgroud)