Search code examples
angulartabsangular-materialmat-tab

How to make different MAT-TAB share same HTML code


I have set of mat-tab in a mat-tab-group, the thing is they all share the same HTML code of a table which is being dynamically filled via functions which i am capturing on tab click event.

following is some code,

<mat-tab-group (selectedTabChange)="tabClick($event)" [hidden]=isPageLoading() [@fadeIn]>
    <mat-tab label="A">
        <HTML CODE>
    </mat-tab>
    <mat-tab label="B">
        <HTML CODE>
    </mat-tab>
    <mat-tab label="C">
        <HTML CODE>
    </mat-tab>
</mat-tab-group>

As i am already filling the tabs with this function,

tabClick(event: any) {
    console.log(event.index);
    switch (event.index) {
      case 0: 
      this.populateA('','1','999999');
      console.log('Author');
        break;
      case 1: 
      this.populateB('','1','999999');
      console.log('Form');
        break;
      case 2: 
      this.populateC('','1','999999');
      console.log('Location');
        break;
}

As you can see there is no need of writing that HTML multiple times, how can i share the same code for all tabs, pseudo-code will be like,

<mat-tab-group (selectedTabChange)="tabClick($event)" [hidden]=isPageLoading() [@fadeIn]>
    <mat-tab label="A">
    <mat-tab label="B">
    <mat-tab label="C">
        <HTML CODE>
    </mat-tab>
    </mat-tab>
    </mat-tab>
</mat-tab-group>

Solution

  • You can use ng-template for this:

    <mat-tab-group (selectedTabChange)="tabClick($event)" [hidden]=isPageLoading() [@fadeIn]>
        <mat-tab label="A">
             <ng-container *ngTemplateOutlet="tabContent"></ng-container>
        </mat-tab>
        <mat-tab label="B">
             <ng-container *ngTemplateOutlet="tabContent"></ng-container>
        </mat-tab>
        <mat-tab label="C">
             <ng-container *ngTemplateOutlet="tabContent"></ng-container>
        </mat-tab>
    </mat-tab-group>
    
    <ng-template #tabContent >
       <HTML CODE>
    </ng-template>
    

    EDIT:

    A working https://stackblitz.com/edit/angular-yqdsr6 with the answer.

    With multiple mat-paginator you'll have to use @ViewChildren instead of @ViewChild

    I also had to tweak the imports in your app.module.ts