Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Material Tabs Load on Tab Select

Is it possible to achieve lazy loading on Angular Material Tabs? Otherwise I would need a way to run a method when entering a tab.

like image 606
Adrian Olosutean Avatar asked Aug 31 '17 10:08

Adrian Olosutean


3 Answers

I know the question was about angular-material 5.x.x, but for those who arrive here and aren't paying attention, angular-material 6 supports lazy-loading tab content natively https://material.angular.io/components/tabs/overview#lazy-loading.

like image 196
papiro Avatar answered Nov 06 '22 18:11

papiro


You can use the selectChange event provided by <md-tab-group>. It fires when a tab selection is changed. From the documentation:

@Output() selectChange : Event emitted when the tab selection has changed.

In your template:

<md-tab-group (selectChange)="tabSelectionChanged($event)">
  <md-tab label="Tab 1">Content 1</md-tab>
  <md-tab label="Tab 2">
    This tab will load some morecontents after 5 seconds.
    <p>{{ moreContents }}</p>
  </md-tab>
</md-tab-group>

... and in your typescript code:

tabSelectionChanged(event){
    // Get the selected tab
    let selectedTab = event.tab;
    console.log(selectedTab);

    // Call some method that you want 
    this.someMethod();
}

Link to working demo.

like image 5
Faisal Avatar answered Nov 06 '22 16:11

Faisal


According to Angular Material Documentation:

Lazy Loading

By default, the tab contents are eagerly loaded. Eagerly loaded tabs will initalize the child components but not inject them into the DOM until the tab is activated.

If the tab contains several complex child components or the tab's contents rely on DOM calculations during initialization, it is advised to lazy load the tab's content.

Tab contents can be lazy loaded by declaring the body in a ng-template with the matTabContent attribute.

<mat-tab-group>
  <mat-tab label="First">
    <ng-template matTabContent>
      The First Content
    </ng-template>
  </mat-tab>
  <mat-tab label="Second">
    <ng-template matTabContent>
      The Second Content
    </ng-template>
  </mat-tab>
</mat-tab-group>
like image 3
FBaez51 Avatar answered Nov 06 '22 17:11

FBaez51