【问题标题】:Typescript error: @viewChild undefined打字稿错误:@viewChild 未定义
【发布时间】:2017-12-22 21:45:48
【问题描述】:

尝试使用 Ionic Tabs 文档中 tabs.ts 中的 select() 方法。但似乎当我尝试运行它时,它说“选择未定义”,当我尝试使用 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);
    }
  }
}

【问题讨论】:

    标签: angular typescript ionic2 ionic3


    【解决方案1】:

    就像你在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);
     }
    
    }
    

    【讨论】:

    • 谢谢!现在能看懂了!
    猜你喜欢
    • 2018-04-20
    • 2018-06-05
    • 1970-01-01
    • 2021-02-14
    • 2023-02-09
    • 2019-05-01
    • 2022-09-27
    • 2016-11-06
    • 1970-01-01
    相关资源
    最近更新 更多