agnimitra
agnimitra

Reputation: 33

Angular 4 nested *ngFor for a number of times

I have one Json object containing file hierarchy list like below:

{
    "path": "\\Users\\ad00440946\\Downloads\\Angular2-
                 GettingStarted-master",
    "name": "Angular2-GettingStarted-master",
    "type": "folder",
    "children": [
        {
           "path": 
               "\\Users\\ad00440946\\Downloads\\Angular2-
                GettingStarted-master/Angular2-GettingStarted-master",
            "name": "Angular2-GettingStarted-master",
            "type": "folder",
           "children": []
        }
   ]
 }

And the list goes on till it reaches to end of a file where children array will be empty. i have to print all this files in a tree view like this. The layout is working fine but problem is i don't know how many levels of children it will have and how many times do i need to iterate. Is there any work arround?

Here's my HTML code:

<!--FILE TREE START-->
<div class="TreeContainer" *ngIf="!searchViewFlag">
    <div class="ParentPlace">
        <span>{{allFilesData.name}}</span>
    </div>
    <br><br>
    <ul class="tree">
        <li *ngFor="let childl1 of allFilesData.children">
            <!--<span>1</span>-->
            <img src="../../assets/Images/ChildNode.png" />
            <a> {{childl1.name}} </a>
            <ul>
                <li *ngFor="let childl2 of childl1.children">
                    <!--<span>3</span>-->
                    <img src="../../assets/Images/ChildNode.png" />
                    <a>{{childl2.name}}</a>
                    <ul>
                        <li *ngFor="let childl3 of childl2.children">
                            <!--<span>3</span>-->
                            <img src="../../assets/Images/ChildNode.png" />
                            <a>{{childl3.name}}</a>
                        </li>
                    </ul>

                </li>
            </ul>
        </li>


    </ul>
</div>

Upvotes: 1

Views: 2782

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71891

You should make a separate component which renders children, which you can use in your parent:

<div class="TreeContainer" *ngIf="!searchViewFlag">
  <tree-item [data]="allFilesData"></tree-item>
</div>

And have a TreeItemComponent which you can repeat if the data has children:

@Component({
  selector: 'tree-item',
  template: `
    <div class="ParentPlace">
      <span>{{data.name}}</span>
    </div>
    <ul *ngIf="data.children && data.children.length > 0">
       <li *ngFor="let child of data.children">
         <tree-item [data]="child"></tree-item>
       </li>
    </ul>
  `
})
export class TreeItemComponent {
  @Input()
  public data: any = {};
}

beware that this is untested code, and merely a guideline for you. Basic concept is, use a component which renders children, and will render children of children if it's necessary

Upvotes: 2

Related Questions