gpt4 book ai didi

angular - typescript 错误 : @viewChild undefined

转载 作者:太空狗 更新时间:2023-10-29 17:19:45 29 4
gpt4 key购买 nike

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

ionic 选项卡文档链接: 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>

标签.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中看到的一样,

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!
}

// ...

}

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

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

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

export class TabsPage {

@ViewChild('myTabs') tabRef: Tabs;

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

}

关于angular - typescript 错误 : @viewChild undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45159753/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com