Error in Typescript: Cannot find reference to @viewChild

I attempted to use the select() method in tabs.ts based on the Ionic Tabs documentation. However, upon running it, I encountered an error stating that "select is undefined". Upon further investigation, I realized that my viewChild was empty or undefined when I logged it using console.log(tabs). I tried to search for reasons why the viewChild is undefined but couldn't grasp the explanation.

For more information, you can refer to the Ionic Tabs documentation: https://ionicframework.com/docs/api/components/tabs/Tabs/

Here is a snippet from 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>

And here is a snippet from 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);
    }
  }
}

Answer №1

As mentioned in the Angular Docs,

The ViewChild property is initialized after the view has been set up.

and

The ViewChild property is updated after the view has been checked.

export class AfterViewComponent implements  AfterViewChecked, AfterViewInit {

  ngAfterViewInit() {
    // The ViewChild property is set after the view has been initialized <- Here!
  }

  ngAfterViewChecked() {
    // The ViewChild property is updated after the view has been checked <- Here!
  }

  // ...

}

The issue with your code is that it tries to interact before the view is fully initialized during the constructor execution. It would be best to move the code that interacts with the tabs into the ngAfterViewInit lifecycle hook:

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

If you prefer to use Ionic custom lifecycle events, consider using the ionViewDidEnter hook:

export class TabsPage {

@ViewChild('myTabs') tabRef: Tabs;

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

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am attempting to activate the "about us" button on the website. I have successfully included the path and added a router link to the containing div of the button. However, there seems to be something

In my app, the first step involves specifying the path in the routing module. Following that is defining the home component, then the app component, and finally creating the button using HTML. Setting up the path in the app.routing.module.ts file <div ...

Scroll horizontally in Ionic 3 without displaying the scrollbar by implementing a button

Is there a way to implement ion scroll in such a manner that upon clicking the right arrow button, it smoothly transitions to the next element within the div section of ion content in Ionic 3 without displaying any scrollbar? I want the scrollbar to remain ...

Disable and grey out the button while waiting for the Observable to broadcast successfully

component.html <button mat-raised-button color="primary" type="submit"> <mat-icon>account_box</mat-icon> <span *ngIf="!loading">&nbsp;&nbsp;&nbsp;Register</span> <span * ...

The data type 'string[]' cannot be assigned to the data type 'listData[]'

I'm currently developing a flexible component that allows the list view to be utilized by different components. However, the challenge arises from the fact that each component has a different data format. In my project, I'm unable to use type any ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

Is it possible to customize the visible columns in a mat table based on the size of the screen?

Using mat-table, I have specified the columns to display in an array: In TypeScript: displayedColumns: string[] = ['date', 'customer', 'project', 'performanceRecord', 'duration', 'status', &apos ...

Creating an enum in TypeScript can be accomplished by using the enum

What transformations do enums undergo during runtime in the TypeScript environment? Fruit.ts enum Fruit {APPLE, ORANGE}; main.ts let basket = [Fruit.APPLE, Fruit.ORANGE]; console.log(basket); The resulting main.js file remains identical to the .ts ver ...

After updating Jest, encountering an error when trying to access the 'html' property of an undefined value

In upgrading jest to version 28 for my angular v12 project, I encountered an error after the update: FAIL src/app/components/update-input/update-input.directive.spec.ts ● Test suite failed to run TypeError: Cannot read property 'html' of un ...

Tips for utilizing the @Input() property of a component to set the initial value of an input field

Is there a way to utilize the value of an @Input() property on Component B as the initial value for an input field in that component when it is contained within Component A? I attempted passing the value during form construction, but found that it only wo ...

Click on the button to open the generated link in a new tab

How can I efficiently open a URL in a new tab after making an API call with the click of a button? Currently, the button triggers the API call and generates the URL. <button (click)="getUrl()">Connect</button> In TypeScript: getUrl() ...

Exploring Heroes in Angular 2: Retrieving Object Information by Clicking on <li> Items

Currently, I am delving into the documentation for an angular 4 project called "Tour of Heroes" which can be found at https://angular.io/docs/ts/latest/tutorial/toh-pt2.html. <li *ngFor="let hero of heroes" (click)="onSelect(hero)">{{hero.name}}< ...

Encountered an error while trying to load config.ts file because of an issue

Trying to set up a new protractor project to conduct tests on an angular site. Node.js, typescript, protractor, and jasmine are all installed globally. After running webdriver-manager update and webdriver-manager start in the project folder, I proceed to b ...

Accessing items in a list generated by ngFor in Angular 6 using checkboxes

I need help with displaying an array using ngFor in Angular (specifically Angular 6). I want to be able to select certain cars by checking a checkbox, and then purchase the selected cars when I press a button. Although the list and checkboxes display corr ...

Storing a portion of JSON data within a function called in the HTML document

I've been working with Angular and need to save a portion of JSON data in a variable within a function that is called in an HTML file: <select id="postazione" onchange="postazioneSelezionata()"> <option value="" selected disabled >Cho ...

Can InstanceType<T> be utilized with an abstract class?

My intention is to enable it to reference implementations rather than the abstract itself, all while exclusively depending on the definitions in the abstract interface. ...

Error: The Select2 query service is not available

I am looking to enhance the search functionality for my select2 dropdown. My goal is to trigger a service call with the search parameters once 3 characters are typed into the search field. However, when I try to select an option from the dropdown, I encou ...

Error message: "Mismatched data types in Formik errors when utilizing TypeScript"

I have a customized input component for formik which includes an error label if one exists. When I print it like this: {errors[field.name]}, it works. However, {t(errors[field.name]?.toLocaleString())} does not work. import { FieldProps, FormikErrors } ...

Create a user-friendly URL using the Router navigation feature

Currently, I am utilizing the navigate function within the Router class to create a URL from a component: this.router.navigate(['/menu'], { queryParams: { level, parent: name } }); Although it functions correctly in terms of setting this.route.p ...

Having difficulty generating an Angular 5 Universal server application bundle with @ngtools/webpack

I am currently working on developing a cross-platform app using Angular 5 and WebPack without utilizing the CLI. The main issue I am facing is that I am unable to get the express application to function properly, resulting in encountering the following er ...

pick only one option from each row

I am working on a feature where I have five rows with two checkboxes each generated using a loop and property binding. Currently, clicking on one checkbox selects all elements in the column. However, I want to achieve selection row-wise. Is there a method ...