1
votes

I'm working on a ng-bootstrap component ngb-tabset. I have 2 tabs, each containing a child component.

<ngb-tabset #tabSet="ngbTabset" *ngIf="!user; else userView">
<ngb-tab id="child1" title="Child 1">
    <ng-template ngbTabContent>
      <mt-child-one></mt-child-one>
    </ng-template>
  </ngb-tab>
  <ngb-tab id="child2" title="Child 2">
    <ng-template ngbTabContent>
      <mt-child-two></mt-child-two>
    </ng-template>
  </ngb-tab>
</ngb-tabset>
<ng-template #userView>
<mt-user></mt-user>
</ng-template>

In my component.ts file, I'm trying to access the reference of these two child, like:

@ViewChild(Child1Component) child1Component: Child1Component;
@ViewChild(Child2Component) child2Component: Child2Component;

The problem I'm facing here is inside my ngOnInit, I can access my active tab component reference, but cannot get the reference for the inactive tab.

I tried with putting the inactive tab under afterViewInit, but still, it returns undefined. Can anyone guide what am I doing wrong here?

1

1 Answers

2
votes

If you add [destroyOnHide]="false" to the ngb-tabset that will prevent Angular destroying a tab when it is hidden (source: NgbTabset docs )

<ngb-tabset #tabSet="ngbTabset" *ngIf="!user; else userView" [destroyOnHide]="false">
  <ngb-tab id="child1" title="Child 1">
      ...
  </ngb-tab>
  <ngb-tab id="child2" title="Child 2">
      ...
  </ngb-tab>
</ngb-tabset>

This means you can then access both tabs (the visible and hidden) in the ngAfterViewInit of the component:

Note: you will need to use AfterViewInit rather than OnInit

Please see this Stackblitz for a demo (just open the console and you should see the following logging):

enter image description here