Angular - 将 td 标签动态划分为单独的列
我试图将表元素动态划分为它自己的单独列。我想要的输出如下所示:
姓名的值始终为 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 放在字符串上时,它工作错误。
I´m trying to divide dynamically the table element to it´s own separate columns. My desired output looks like this:
Value for name and surname is always 1, but values for subjects and grade are dynamic (there can be 2 columns or more).
This is my data:
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>
Here is a stackblitz example: https://stackblitz.com/edit/angular-pzgohu
Does anybody know what could be solution? I tried to put span inside td tag and loop through the .length, but it works wrong when I put length on string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用基于行值的条件,也可以使用 typeof 来检查它是字符串还是数组 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
You can either use condition based on row value or you can use typeof to check if it is a string or array https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof