[英]Angular passing index from parent to child in nested *ngFor
I want to display content with bunch of nested *ngFor loops and I want to keep track of the index of previous ngFor loop as a parent index.我想用一堆嵌套的 *ngFor 循环显示内容,并且我想跟踪前一个 ngFor 循环的索引作为父索引。 I couldn't find a way to pass the index of previous loop to the current one.
我找不到将前一个循环的索引传递给当前循环的方法。
Here is what I try (doesn't work):这是我尝试的(不起作用):
<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>
Is there any way that enable me to add previous index
to parentIndex
variable like above?有什么方法可以让我像上面那样将以前的
index
添加到parentIndex
变量?
This is the example output that I want to achieve.这是我想要实现的示例 output。
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
Here is the example of object that I used这是我使用的 object 的示例
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"]
}
]
}
]
Just use different local variable names for each *ngFor
's index.只需为每个
*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>
Working example: Stackblitz工作示例: Stackblitz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.