2017-07-18 141 views
2

嘗試從Ionic選項卡文檔的tabs.ts中使用select()方法。但似乎當我嘗試運行它時,它說「select is undefined」,我發現我的viewChild實際上是空的/未定義,當我嘗試console.log(標籤)。試圖尋找爲什麼viewChild未定義,但無法真正理解爲什麼的原因。Typescript錯誤:@viewChild undefined

鏈接到離子標籤文檔: 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

就像你可以在Angular Docs看到,

ViewChild is set after the view has been initialized

ViewChild is updated after the view has been checked

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

如果你只是想用離子定製生命週期事件,你需要使用ionViewDidEnter鉤:

export class TabsPage { 

@ViewChild('myTabs') tabRef: Tabs; 

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

} 
+1

Thnx!能夠理解它! –

+0

我很高興聽到! :) – sebaferreras