Rajath
Rajath

Reputation: 2980

How to display the table headers in a row, in angular material table?

My Material table displays the value in below manner:

Name |quatity

Mango|10

    <div class="table-cover center-table">
      <div class="mat-elevation-z8 elevation-scroll-control">
        <table mat-table class="full-width-table left-margin" [dataSource]="dataSource" matSort aria-label="Elements">

          <!-- Name Column -->
          <ng-container matColumnDef="name">
            <td mat-header-cell *matHeaderCellDef >Name</td>
            <td mat-cell *matCellDef="let row" class="">
              <div class="cell-style padding-left">{{row.Name}}</div>
            </td>
          </ng-container>

          <!-- quantity Column -->
          <ng-container matColumnDef="quantity">
            <td mat-header-cell *matHeaderCellDef>quantity</td>
            <td mat-cell *matCellDef="let row">
              <div class="cell-style">{{row.quantity}}</div>
            </td>
          </ng-container>

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

      </div>      
    </div>

But I want to display the value like below:

Name | Mango

quatity | 10

How can I achieve this? any help is much appreciated

Upvotes: 6

Views: 15001

Answers (1)

GCSDC
GCSDC

Reputation: 3540

You may do that by:

  1. Transposing your data from columns to row:

    Before: Mango |10 Banana|5

    After: Mango|Banana 10|5

  2. Including the labels as the first column of your data:

    Name|Mango|Banana Quantity|10|5

  3. Adjust your table to display columns dynamically (so that you may have any number of columns), as on this example from angular material table documentation:

<table mat-table [dataSource]="data" class="mat-elevation-z8">
  <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
    <th mat-header-cell *matHeaderCellDef> {{column}} </th>
    <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
  <tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
</table>
  1. If not required you may remove the header row

  2. If you want to format the first column, you may use some css as:

    td.mat-cell:nth-child(1) { // formatting }

  3. Also, if required, you may use property sticky of MatColumnDef to keep the first column sticky (in this case you may want to have the first column separate from the dynamic *ngFor loop, so that you may easily have only the first column sticky)

I've created a working stackblitz example

Upvotes: 5

Related Questions