打字稿错误:@viewChild未定义



尝试使用Ionic Tabs文档中tabs.ts中的select((方法。但是似乎当我尝试运行它时,它说"选择未定义",并且当我尝试控制台.log(选项卡(时,我发现我的viewChild实际上是空的/未定义的。尝试搜索 viewChild 未定义的原因,但无法真正理解原因。

链接到离子标签文档: https://ionicframework.com/docs/api/components/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>

标签.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);
}
}
}

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

视图子项是在视图初始化后设置的

检查视图后更新

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

相关内容

  • 没有找到相关文章

最新更新