Reputation: 373
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. 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?
This is the example output that I want to achieve.
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
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"]
}
]
}
]
Upvotes: 1
Views: 1948
Reputation: 31105
Just use different local variable names for each *ngFor
's index.
<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
Upvotes: 2