我正在嘗試將表格元素動態劃分為它自己的單獨列。我想要的輸出如下所示:
姓名和姓氏的值始終為 1,但科目和年級的值是動態的(可以有 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 標記內并回圈遍歷 .length,但是當我將 length 放在字串上時它會出錯。
uj5u.com熱心網友回復:
您可以使用基于行值的條件,也可以使用 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/431289.html
標籤:javascript html 有角度的 打字稿 html表
