Access component using viewChild() within ng-tempalte

42 Views Asked by At

I am implementing nested tabs in angular using ngb-tabset and I am having difficulty while using viewChild for nested tabs. it got the undefined value. the inner tabs are rendering within ng-template that is causing this issue. I want to set the second tab active for inner tabs instead of default one which is first tab. Any help much appreciated!

here is the html:

<div class="card-block">
    <ngb-tabset #tabset (tabChange)="onTabChange($event.nextId)" class="profile-container">
        <ngb-tab id="a" class="w-100 h-100">
            <ng-template ngbTabTitle>A</ng-template>
            <ng-template ngbTabContent>
            
            </ng-template>
        </ngb-tab>
        <ngb-tab id="b" class="w-100 h-100">
            <ng-template ngbTabTitle>B</ng-template>
            <ng-template ngbTabContent>
                <ng-content *ngTemplateOutlet="innerTabset"></ng-content>
            </ng-template>
        </ngb-tab>
        <ngb-tab id="c" class="w-100 h-100">
            <ng-template ngbTabTitle>C</ng-template>
            <ng-template ngbTabContent>
                
            </ng-template>
        </ngb-tab>
    </ngb-tabset>
</div>

<ng-template #innerTabset>
    <ngb-tabset #tabset1 (tabChange)="onInnerTabChange($event.nextId)" class="profile-container">
                    <ngb-tab id="b1" class="w-100 h-100">
                        <ng-template ngbTabTitle>b1</ng-template>
                        <ng-template ngbTabContent>
                        
                        </ng-template>
                    </ngb-tab>
                    <ngb-tab id="b2">
                        <ng-template ngbTabTitle>b2</ng-template>
                        <ng-template ngbTabContent>
                            <div class="w-100 h-100">
                                
                            </div>
                        </ng-template>
                    </ngb-tab>
                    <ngb-tab id="b3" class="w-100 h-100">
                        <ng-template ngbTabTitle>b3</ng-template>
                        <ng-template ngbTabContent>
                            
                        </ng-template>
                    </ngb-tab>
                </ngb-tabset>
</ng-template>

here is the code in ts file:

@ViewChild('tabset', {static: false}) tabset : NgbTabset;
  @ViewChild('tabset1', { static: false }) tabset1 : NgbTabset;

  tab: string
  
  constructor(
    private router: Router,
    private cd: ChangeDetectorRef
  ) {
    
  }

  ngAfterViewInit(): void  {
    console.log('tabs', this.tabset);
    console.log('tabs1', this.tabset1);
    this.tabset.activeId = "b";
    this.tabset1.activeId = "b2";
  }

this.tabset is working fine which is parent tab but tabset1 is returning undefined so could not set active tab of my choice.

0

There are 0 best solutions below