如何在角度4中使用* ngFor循环多维对象 [英] how to loop multidimensional object with *ngFor in angular 4
问题描述
我尝试在我的html中使用 * ngFor
循环该对象.
I try to loop that object with *ngFor
in my html.
<tr *ngFor="let artikel of artikels">
</tr>
但是那给了我错误
有人可以帮助我如何循环播放此对象吗?
Can somebody help me how to loop this object?
我也是角度的新手.谢谢!
I'm new to angular too.. Thanks!!
推荐答案
您无法使用* ngFor遍历对象,因为错误提示您需要使用类似数据结构的数组.
You can't iterate over objects with *ngFor, as the error say's you need to use an array like data structure.
最好的解决方案是将管道与* ngFor一起使用,以将对象转换为数组.
The best solution is to use pipe with your *ngFor that transform your object into an array.
尝试将此管道添加到您的util的模块中:
Try to add this pipe to your util's module:
@Pipe({name: 'objectToArray'})
export class objectToArray implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push(key);
}
return keys;
}
将管道导入模块并与* ngFor
Import the pipe into your module and use it with your *ngFor
<tr *ngFor="let articleKey of article|objectToArray">
</tr>
现在,您可以使用"articleKey"并将其用于遍历嵌套数组:
Now you can use 'articleKey' and use it to loop over the nested array:
<tr *ngFor="let articleKey of article|objectToArray">
<td *ngFor="let article of article[articleKey]">
<!--your template-->
</td>
</tr>
这篇关于如何在角度4中使用* ngFor循环多维对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!