Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mat-tab lazy load tab only once

I am using Angular Material mat-tab and it is set to lazy load the tabs content.

Since the first tab is loaded by default I have set second tab to load lazily.

I see that when I navigates between the tabs repeatedly, the second tab's content is loading freshly every time. I have a Web API call to get data and show in the tab content.

So I want to avoid the Web API call every time the tab is selected. How can I achieve that?

<mat-tab-group>
  <!--Roles Tab-->
  <mat-tab class="tabLabel" label="Roles">
    <app-roles></app-roles>
  </mat-tab>
  <!--Admins Tab-->
  <mat-tab class="tabLabel" label="Admins">
    <!-- Lazy load below component -->
    <ng-template matTabContent>
      <app-admins></app-admins>
    </ng-template>
  </mat-tab>
</mat-tab-group>
like image 877
Sushrut Paranjape Avatar asked Oct 10 '18 15:10

Sushrut Paranjape


Video Answer


1 Answers

Use the event selectedIndexChange on mat-tab-group and put your content in a div with ngIf,like this:

<mat-tab-group (selectedIndexChange)="tabChange($event)">
  <mat-tab label="Today">
    <ng-template matTabContent>
    <hello name="{{ name }}"></hello>
    </ng-template>
  </mat-tab>
   <mat-tab label="Yesterday">
     <div *ngIf="yesterDayTabShow">
    <hello name="Test"></hello>
     </div>
  </mat-tab>
</mat-tab-group>

See the link: https://stackblitz.com/edit/angular-tu7jsg

like image 54
Jiang Zheqi Avatar answered Sep 22 '22 21:09

Jiang Zheqi