NativeScript separated tab component


I’m using NativeScript Angular for my application. I created a tab component. The idea is that each tab must contain it’s own logic. For example, I have an alert in each component constructor. But they are all shown when app starts running.

My structure:

  • AppComponent
  • TabComponent
    • TabOneComponent
    • TabTwoComponent
    • TabThreeComponent

AppComponent.html :

<ActionBar title="Hello World" class="action-bar"></ActionBar>


<TabView #tabview [selectedIndex]="tabindex" sdkExampleTitle sdkToggleNavButton>
    <StackLayout *tabItem="{title: 'Tab One'}">
    <StackLayout *tabItem="{title: 'Tab Two'}">
    <StackLayout *tabItem="{title: 'Tab Three'}">


<Label text="tab one"></Label>

Any idea?


So the issue is that an alert is shown when each tab is created, rather than when you click on a tab, is that right?


Yes, exactly. The main idea is that. All of constructors are going to run, rather than clicking on each tab and running it’s own constructor.

And if possible to cache the view of each tab (ex. alerting just for once when you go through the tabs).


@jen.looper Any idea?


I haven’t tested it, but I feel like splitting up your code into separate components and modules might help. Then you can lazy load your modules when the tab is clicked. This is pure hypothesis…


You may want to research Angular life cycle events. The reason why all your alerts are firing at the same time, is constructors are fired for components, prior to them actually being rendered. The component’s class is instantiated and per any programing language, the constructor is fired by default.

How I would personally attack your problem:

Option 1

Use *ngIf constraints on your child components, dependent on that tab actually being active. You can either do this by the tabindex variable you have, or comparing the title of the active tab.

Move your alert logic in each subsequent child component, into the OnInit lifecycle hook (ngOnInit). This should be dispatched each time the tab is set to active.

Option 2
I would assume the TabView has an event hook for when the selected index changes. The syntax sugar for most Angular events is something like: [(selectedIndex]) to handle both the Input and Output hooks. You could use this event emit, to specify the specific alert you want to display.


@jen.looper Thanks, I will give it a try.


@sean-perkins Thank you so much about good ideas. But first one does not seem very good practice. As I used to work with angularjs 1.x , I feel there must be something about routing, as Ionic framework represent very nice logic about tabs with routing, caching mechanism and some events (ex. onViewEnter).

You may want to research Angular life cycle events

Yes, thanks about your help.