[英]Angular - divide td tag into separate columns dynamically
我試圖將表格元素動態划分為它自己的單獨列。 我想要的 output 看起來像這樣:
name 和 surname 的值始終為 1,但 subjects 和 grade 的值是動態的(可以有 2 列或更多)。
這是我的數據:
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','English'],
grade: ['A','A','B'],
},
];
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.charAt(0).toUpperCase() + row.slice(1) }}</th>
<td *ngFor="let item of data">{{ item[row] }}</td>
</tr>
</tbody>
</table>
這是一個 stackblitz 示例: https://stackblitz.com/edit/angular-pzgohu有人知道什么是解決方案嗎? 我試圖將 span 放在 td 標記內並循環遍歷 the.length,但是當我將 length 放在字符串上時它會出錯。
您可以使用基於行值的條件,也可以使用 typeof 來檢查它是字符串還是數組https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
<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.charAt(0).toUpperCase() + row.slice(1) }}</th>
<td *ngFor="let item of data">
<span *ngIf="row !== 'subjects' && row !== 'grade'">
{{ item[row] }}
</span>
<table *ngIf="row === 'subjects' || row === 'grade'">
<tr>
<td *ngFor="let subItem of item[row]">
{{ subItem }}
</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.