问题
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:
Transposing your data from columns to row:
Before: Mango |10 Banana|5
After: Mango|Banana 10|5
Including the labels as the first column of your data:
Name|Mango|Banana Quantity|10|5
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>
If not required you may remove the header row
If you want to format the first column, you may use some css as:
td.mat-cell:nth-child(1) { // formatting }
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