Angular 4 Material Tabs Load on Tab Select

前端 未结 4 1010
失恋的感觉
失恋的感觉 2021-01-03 04:51

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.

相关标签:
4条回答
  • 2021-01-03 05:14

    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.

    0 讨论(0)
  • 2021-01-03 05:23

    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.

    0 讨论(0)
  • 2021-01-03 05:32

    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.

    0 讨论(0)
  • 2021-01-03 05:35

    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>
    
    0 讨论(0)
提交回复
热议问题