Stack Overflow
Stack Overflow

Reputation: 2764

Mat-tab load inner component after selected tab

I am using Mat-tab in Angular material 7.2.1 version

Each tab contains a different component.

Like below:

<mat-tab-group>
  <mat-tab>
    <ng-template mat-tab-label>
      <span>Map</span>
    </ng-template>
      <app-health-education-map></app-health-education-map>
  </mat-tab>
  <mat-tab>
    <ng-template mat-tab-label>
      <span>Form</span>
    </ng-template>
    <app-health-education-form></app-health-education-form>
  </mat-tab>
</mat-tab-group>

Using ngOnInit event in inner component to load the data, hits when the page is loaded and not when tab selected.

How can I change this behavior?

Upvotes: 0

Views: 4810

Answers (1)

Lia
Lia

Reputation: 11982

Try to trigger change in tab:

<mat-tab-group selectedIndex="0" (selectedTabChange)="changeTab($event)">
  <mat-tab>
    <ng-template mat-tab-label>
      <span>search</span>
    </ng-template>
      <app-search></app-search>
  </mat-tab>
  <mat-tab>
    <ng-template mat-tab-label>
      <span>home</span>
    </ng-template>
    <app-home  *ngIf="tabIndex === 1"></app-home>
  </mat-tab>
</mat-tab-group>

ts:

tabIndex = 0 ;

changeTab(event){
   this.tabIndex = event.index;
}

DEMO the name will be appear after 5 seconds of initializing the inner component.

Upvotes: 3

Related Questions