Adrian Olosutean
Adrian Olosutean

Reputation: 179

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.

Upvotes: 5

Views: 15466

Answers (4)

FBaez51
FBaez51

Reputation: 551

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>

Upvotes: 5

papiro
papiro

Reputation: 2365

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.

Upvotes: 7

FAISAL
FAISAL

Reputation: 34673

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.

Upvotes: 5

Vikhyath Maiya
Vikhyath Maiya

Reputation: 3192

As the documentation reads

While <md-tab-group> is used to switch between views within a single route, <nav md-tab-nav-bar> provides a tab-like UI for navigating between routes.

By using this method,you can make each of the tab separate routes and hence each of the page loads each time the route is activated.

<nav md-tab-nav-bar>
  <a md-tab-link
     *ngFor="let link of navLinks"
     [routerLink]="link"
     routerLinkActive #rla="routerLinkActive"
     [active]="rla.isActive">
    {{tabLink.label}}
  </a>
</nav>

<router-outlet></router-outlet>

Please find more info here under Tabs and navigation section.

Upvotes: 1

Related Questions