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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With