我想用一堆嵌套的*ngFor循环来显示内容,并且我想跟踪上一个ngFor循环的索引作为父索引。我找不到将上一个循环的索引传递到当前循环的方法。
以下是我尝试的(不起作用(:
<div *ngFor="let parent of content; index as i" >
<span>{{parent.name}} index - {{i}}</span>
<div *ngFor="let child of parent.childreen; i as parentIndex, index as i" >
<span>{{child.name}} index - {{i}} parentIndex - {{parentIndex}} </span>
<div *ngFor="let child of child.childreen; i as parentIndex, index as i">
<span>{{child}} index - {{i}} parentIndex - parentIndex</span>
</div>
</div>
</div>
有什么方法可以让我像上面那样将以前的index
添加到parentIndex
变量中吗?
这是我想要实现的示例输出。
Parent 1 index - 0
Child 1.1 index - 0 parentIndex - 0
Child 1.1.1 index - 0 parentIndex - 0
Child 1.1.2 index - 1 parentIndex - 0
Child 1.1.3 index - 2 parentIndex - 0
Child 1.2 index - 1 parentIndex - 0
Child 1.2.1 index - 0 parentIndex - 1
Child 1.2.2 index - 1 parentIndex - 1
Child 1.2.3 index - 2 parentIndex - 1
Parent 2 index - 1
Child 2.1 index - 0 parentIndex - 1
Child 2.1.1 index - 0 parentIndex - 0
Child 2.1.2 index - 1 parentIndex - 0
Child 2.1.3 index - 2 parentIndex - 0
Child 2.2 index - 1 parentIndex - 1
Child 2.2.1 index - 0 parentIndex - 1
Child 2.2.2 index - 1 parentIndex - 1
Child 2.2.3 index - 2 parentIndex - 1
以下是我使用的对象示例
content: any[] = [
{
name: "Parent 1",
childreen: [
{
name: "Child 1.1",
childreen: ["Child 1.1.1", "Child 1.1.2", "Child 1.1.3"]
}, {
name: "Child 1.2",
childreen: ["Child 1.2.1", "Child 1.2.2", "Child 1.2.3"]
}]
}, {
name: "Parent 2",
childreen: [
{
name: "Child 2.1",
childreen: ["Child 2.1.1", "Child 2.1.2", "Child 2.1.3"]
}, {
name: "Child 2.2",
childreen: ["Child 2.2.1", "Child 2.2.2", "Child 2.2.3"]
}
]
}
]
只需为每个*ngFor
的索引使用不同的局部变量名。
<div *ngFor="let parent of content; index as i">
<span>{{parent.name}} index - {{i}}</span>
<div *ngFor="let child of parent.childreen; index as j">
<span>{{child.name}} index - {{j}} parentIndex - {{i}}</span>
<div *ngFor="let child of child.childreen; index as k">
<span>{{child}} index - {{k}} parentIndex - {{i}} </span>
</div>
</div>
<br>
</div>
更新
工作示例:Stacklitz