问题
I'm creating a table with PrimeNG for an Angular app. It shall show the number of students by class. What I magaged to build is a table with one column for class names and one column to the number of students. What I need is one ROW for class names and one for the number of students. Is there a (clean code compatible) way to transpose a table?
Here is the table html:
<p-table [value]="getData()">
<ng-template pTemplate="header">
</ng-template>
<ng-template pTemplate="body" let-data>
<tr>
<td class="legend-cell" >
{{data.className}}
</td>
<td class="non-edit-cell" >
{{data.numStudents}}
</td>
</tr>
</ng-template>
</p-table>
This is my dummy data:
getData(){
let data = [];
data.push({className: 'Class 1', numStudents: 22})
data.push({className: 'Class 2', numStudents: 23})
data.push({className: 'Class 3', numStudents: 24})
return data;
}
The result table:
What I want (I bloodyly hardcoded this):
回答1:
You can solve it like below. Do not use table instead use <div>
and CSS properties:
<p-table [value]="getData()">
<ng-template pTemplate="body" let-data>
<div style="display:inline-block;">
{{data.className}}
<div>{{data.numStudents}}</div>
</div>
</ng-template>
</p-table>
There could be multiple CSS properties you can use. Like Flex but I just giving you a solution.
回答2:
Ok, there was quite an intuitive solution. I just never saw before on tables:
You can also put rows into columns, not just columns into rows:
<p-table [value]="getData()">
<ng-template pTemplate="header">
</ng-template>
<ng-template pTemplate="body" let-data>
<td>
<tr>{{data.className}}</tr>
<tr>{{data.numStudents}}</tr>
</td>
</ng-template>
</p-table>
You can also do it without rows at all making the first line the header:
<p-table [value]="getData()">
<ng-template pTemplate="header">
<th *ngFor="let class of getData()">{{class.className}}</th>
</ng-template>
<ng-template pTemplate="body" let-data>
<td>
{{data.numStudents}}
</td>
</ng-template>
</p-table>
来源:https://stackoverflow.com/questions/53778273/transpose-html-table-p-table-with-primeng-7-x