我有一个看起来像这样的对象:
obj = {'a': [0, 0, 1, 0], 'b': [1, 0, 0, 1], 'c': [0, 0, 0, 0], 'd': [1, 1, 1, 0]}
我想把它显示在这样的表格中:
No | a | b | c | d
0 | 0 | 1 | 0 | 1
1-3 | 0 | 0 | 0 | 1
4-6 | 1 | 0 | 0 | 1
7-9 | 0 | 1 | 0 | 0
//a //b //c //d
我如何使用 ngFor
做到这一点?
这是我的html
<table>
<thead>
<tr>
<th scope="col">No</th>
<th scope="col">a</th>
<th scope="col">b</th>
<th scope="col">c</th>
<th scope="col">d</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td></td>
</tr>
<tr>
<td>1-3</td>
<td></td>
</tr>
<tr>
<td>4-6</td>
<td></td>
</tr>
<tr>
<td>6-9</td>
<td></td>
</tr>
</tbody>
<table>
如果我尝试遍历obj
,我会得到
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
我该如何解决这个问题?感谢您的时间! Here is a working snippet
最佳答案
您可以使用键值管道:
<div *ngFor="let item of object | keyvalue">
{{item.key}}:{{item.value}}
</div>
文档:https://angular.io/api/common/KeyValuePipe
(适用于 Angular 6.1+)
编辑:
您可以将您的对象更改为:
obj = {'0': [0, 0, 1, 0], '1-3': [1, 0, 0, 1], '4-6': [0, 0, 0, 0], '6-9': [1, 1, 1, 0]}
然后在 html 中:
<tbody>
<tr *ngFor="let x of obj | keyvalue">
<td>{{x.key}}</td>
<td *ngFor="let data of x.value">{{data}}</td>
</tr>
</tbody>
关于html - 迭代对象并将其显示在表 Angular 6 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55223751/