[英]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.