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

守給你的承諾、 提交于 2019-12-22 10:28:00

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/53493197/how-to-display-the-table-headers-in-a-row-in-angular-material-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!