Prata
Prata

Reputation: 1320

Nativescript (typescript) How do I access/get the instance/reference of a component from a different component?

I am trying to access the component(Class instance) of NavigationButton and SearchBar in ActionBar from the component(Class instance) of a tabItem in a TabView. How do I do this?

<ActionBar color="black" title="">
    <NavigationButton #navBtn text="Go Back" android.systemIcon="ic_menu_back" (tap)="goBack()" [visibility]="navBtnVisibility"></NavigationButton>
    <StackLayout *ngIf="tabIndex == 0" titleView orientation="horizontal">
        <SearchBar hint="Search hint" [text]="searchPhrase" (textChange)="onTextChanged($event)" (submit)="onSubmit($event)" 
        color="black" textFieldHintColor="black"></SearchBar>
    </StackLayout>
</ActionBar>

<TabView #tabView [selectedIndex]="tabIndex" (selectedIndexChanged)="tabViewIndexChange(tabView.selectedIndex)">
    <StackLayout *tabItem="{title: 'Search'}" class="tab-item">
        <search-tab>
        </search-tab>
    </StackLayout>
    <StackLayout *tabItem="{title: 'Home'}" class="tab-item">
        <home-tab>
        </home-tab>
    </StackLayout>
    <StackLayout *tabItem="{title: 'Profile'}" class="tab-item">
        <!--<profile></profile>-->
        <profile-tab>
        </profile-tab>
    </StackLayout>
</TabView>

Upvotes: 0

Views: 1550

Answers (3)

Manoj
Manoj

Reputation: 21908

It's possible using ViewChild / ContentChild or even services. But an easiest way I could be by accessing the frame package,

const currentPage = frame.topmost().currentPage

Once you get the current page, you can access it's action bar or any component residing inside the page.

Upvotes: 1

Ron Newcomb
Ron Newcomb

Reputation: 3302

Component to component communication only happens between direct parent-child relationships in Angular 2+. Otherwise you must use an Angular service as a go-between.

So, the pictured component could access ActionBar and TabView with @ViewChild(), and the ActionBar component could access NavigationButton with @ContentChild() since NavigationButton is between <ActionBar>and </ActionBar>, but grandparent, sibling, and cousin relationships require a service go-between.

AngularJS had $parent.$parent.$parent stuff but it was deprecated by style guides for poor architecture.

Upvotes: 0

BionicBear
BionicBear

Reputation: 28

One Possible way to accomplish this is to use a service, bind your references from the Parent Component, and then in your child components you should inject the service.

Upvotes: 1

Related Questions