@ViewChild class is undefined

Hello, I’am new in Ionic 2 and i would like to understand how works ViewChild. I’ve created sample app with Tabs and I would like Set Badges in other clasess than TabsPage.
My Tabs.html

> <ion-tabs id="myTabs">
>   <ion-tab [root]="tab1Root" tabTitle="Home"  tabBadge="{{value}}" tabIcon="home"></ion-tab>
>   <ion-tab [root]="tab2Root" tabTitle="About" tabIcon="information-circle"></ion-tab>
>   <ion-tab [root]="tab3Root" tabTitle="Contact" tabIcon="contacts"></ion-tab>
> </ion-tabs>

My Tabs.ts

@Component({
templateUrl: ‘build/pages/tabs/tabs.html’
})
export class TabsPage {
private tab1Root: any;
private tab2Root: any;
private tab3Root: any;
public value: any;

>   constructor() {
>     // this tells the tabs component which Pages
>     // should be each tab's root Page
>     this.tab1Root = HomePage;
>     this.tab2Root = AboutPage;
>     this.tab3Root = ContactPage;
>     this.value = 1;
>   }
> }

And Here is my contact.ts.

import {Component, ViewChild} from ‘@angular/core’;
import {NavController, Tabs} from ‘ionic-angular’;
import {Contact2} from ‘…/contact2/contact’;
import {TabsPage} from ‘…/tabs/tabs’;

@Component({
templateUrl: ‘build/pages/contact/contact.html’
})
export class ContactPage {
@ViewChild(‘myTabs’) tabRef: TabsPage;
constructor(private navCtrl: NavController) {
}
Test()
{

  this.tabRef.value = 5; 

}
}

On click on button i would like to set value from TabsPage class on 5. But I get error:

ORIGINAL EXCEPTION: TypeError: undefined is not an object (evaluating ‘this.tabRef.value = 5’)

How it works? Is it possible to set this value from other class ? Thanks for help

Do this in your HTML instead of using the id attribute.

<ion-tabs #myTabs>
1 Like

The result is the same :confused:

Sorry, I misread your post. :frowning: I didn’t realize you were trying to reference an element outside of your component.

Is possible to call method from TabsPage in ContatctPage ?

I strongly recommend not doing this. It’s overly tight coupling.

So how cen I set Badges in Tabs ??

I think you should instead consider altering a common model, using observers of some sort, or publishing events.