我有一个嵌套的对象列表,我正在迭代这些对象,每个对象内部都有一个数组。
arr: any[] = [
{ 'title': 'fruits', res: ['apple', 'pear'] },
{ 'title': 'numbers', res: [3, 5, 7, 11] },
{ 'title': 'letters', res: ['a', 'b'] }];
];` 我希望迭代每个嵌套数组res并输出累积索引,以便上面的输出等于以下内容:
fruits
0 - apple
1 - pear
numbers
2 - 3
3 - 5
4 - 7
5 - 11
letters
6 - a
7 - bAngular公开局部变量index,但是是否有一种方法来定义其他局部变量并在我们前进的过程中增加它们。像下面这样的东西(我知道这不会渲染)
<div *ngFor="let list of comboList; let i = index; let count = 0">
<h1>{{ list.title}}</h1>
<div *ngFor="let item of list.res; let j = index; count ++">
{{ count }} - {{ item }}
</div>
</div>到目前为止,我唯一的工作选项是一个函数,每当我想要显示一个项目时,都会调用它,但效率不高。
getCumIndex(arr: any[], x: number, y: number){
let count: number = 0;
for (let i = 0; i < arr.length; i++){
if (x == i){
return count + y;
} else {
count += arr[i].res.length;
}
}
}发布于 2017-03-02 16:03:16
带有自定义管道和帮助器类的解决方案的这是柱塞
<div *ngFor="let counter of [comboList | counterPipe]">
{{ counter.reset() }}
<div *ngFor="let list of comboList">
<h1>{{ list.title }}</h1>
<div *ngFor="let item of list.res">
{{ counter.inc() }} - {{ item }}
</div>
</div>
</div>发布于 2017-03-02 13:42:58
非常简单的解决方案。这是您的模板:
<div *ngFor="let list of comboList; let i = index;">
<h1>{{ list.title}}</h1>
<div *ngFor="let item of list.res; let j = index;">
{{ cumulativeLength(i) + j }} - {{ item }}
</div>
</div>然后在你的控制器里:
cumulativeLength(index) {
let acc = 0;
for (let i = 0; i<index; i++) {
acc += this.comboList[i].res.length;
}
return acc;
}我还没查过但应该能用。
发布于 2017-03-02 13:44:44
除了角预定义的ng属性之外,任何自定义逻辑都应该在组件中完成,而不是在视图中完成。
https://stackoverflow.com/questions/42556286
复制相似问题