Home > Mobile >  Get the mat-table headers in Angular
Get the mat-table headers in Angular

Time:02-21

I have a mat-table in angular and I want to get the header's title of each column using the typescript code, is there any way to do it?

HTML Code:

<mat-table id="emp_table" #table [dataSource]="dataSource" matSort>
    <ng-container matColumnDef="number">
      <mat-header-cell *matHeaderCellDef mat-sort-header > Number
      </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.number}} </mat-cell>
    </ng-container>
    
    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef mat-sort-header > Name
      </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="mobile">
      <mat-header-cell *matHeaderCellDef mat-sort-header > Mobile
      </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.mobile}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>

TS Code:

displayedColumns = ['number', 'name', 'mobile'];

So, what I want is to get the titles: "Number", "Name", "Mobile" from the html using ts all at once using loop, because maybe in the future the table get bigger so I want to get all the titles dynamically.

Thank you.

CodePudding user response:

You can do very easy the other way round, just define the Headers in the code-behind file:

TS Code:

const numberTitle = 'Number';

HTML Code:

<mat-header-cell *matHeaderCellDef mat-sort-header >
    {{ numberTitle }}
</mat-header-cell>

CodePudding user response:

As Efkah says, normally you use the another aproach. You has two variables

  displayedColumns=['number','name','mobile']
  headersColumns=['Number', 'Name','Mobile']

And use:

<ng-container *ngFor="let column of displayedColumns;let i=index"
        [matColumnDef]="column">
  <mat-header-cell *matHeaderCellDef mat-sort-header > 
       {{headers[i]}}
  </mat-header-cell>
  <mat-cell *matCellDef="let row"> {{row[column]}} </mat-cell>
 </ng-container>
  • Related