[英]Angular - using ngFor to display data with column and row headers
我在顯示包含列標題和行標題的表格內的數據時遇到問題。 我試圖通過使用 *ngFor 使其動態化。 你能建議在這種情況下如何處理 *ngFor 嗎?
帶有數據的ts文件:
export class NewScreen {
rows = [
'Name',
'Surname',
'Subjects',
'Grade',
];
data = [
{
student: 'Student 1',
name: 'Alex',
surname: 'Smith',
subjects: ['Math','Geometry'],
grade: ['A','B'],
},
{
student: 'Student 2',
name: 'Michael',
surname: 'Laurent',
subjects: ['Math','Geometry'],
grade: ['B','C'],
},
{
student: 'Student 3',
name: 'Sophie',
surname: 'Miller',
subjects: ['Math','Geometry'],
grade: ['A','A'],
},
];
}
HTML:我一直在嘗試找到放入 {{???}} 的解決方案,這將導致顯示以下表結構,但沒有成功:
<table>
<thead>
<tr>
<th></th>
<th *ngFor="let column of data">{{ column.student }}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of rows">
<th>{{ row }}</th>
<td *ngFor="let value of data | keyvalue">{{ value.value[i + 1] }}</td>
</tr>
</tbody>
</table>
我從 HTML 創建了一個簡單的例子,你提供的數據https://stackblitz.com/edit/angular-vuzjyk
{{ item.value }}
顯示[object Object]
的原因是因為您沒有給它一個標識符來選擇您希望顯示的 object 的屬性。
為了簡化,我更新了您的rows[]
以匹配您的數據鍵以直接使用它。
rows = ['name', 'surname', 'subjects', 'grade'];
在 HTML 中,我只是使用該行來標識我們希望顯示的屬性。 同樣在<th>
中,我將每個 header 的第一個字母大寫。
<tr *ngFor="let row of rows">
<th>{{ row.charAt(0).toUpperCase() + row.slice(1) }}</th>
<td *ngFor="let item of data">
{{ item[row] }}
</td>
</tr>
查看我上面提供的 stackblitz 鏈接,如果您有任何疑問,請隨時詢問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.