1

I am trying to build tree structure using angular 2 with a basic parent-child concept.

component.html template looks like below:

<li class="nav-item " *ngFor="let dir of directories">
    <a href="javascript:;" class="nav-link nav-toggle">
        <i class="fa fa-clock-o"></i>
        <span class="title">{{ dir.name }}</span>
        <span class="arrow"></span>
    </a>
    <ul class="sub-menu" *ngFor="let file of directories.child">
        <li class="nav-item  ">
            <a href="#" class="nav-link ">
                <span class="title">{{file.name}}</span>
            </a>
        </li>
        <navigation-bar [directories]="dir.child"></navigation-bar>
     </ul>
</li>

component.ts file :

import { Component, Input } from '@angular/core';
@Component({
    selector: 'navigation-bar',
    templateUrl: './app/home/navigationBar.component.html',    
})

export class NavigationBarComponent {
    @Input() directories: Array<Tree>;      
}

export class Tree{
    directories: any;
    constructor()
    {
        this.directories = [
        {
            name: 'parent1',
            child: [{
                name: 'child1',
                child: []
            },
            {
                name: 'child2',
                child: []
            }]
        },
        {
            name: 'parent2',
            child: {
                name: 'child1',
                child: []
            }
        },
        {
            name: 'parent2',
            child: [{
                name: 'child1',
                child: []
            },
            {
                name: 'child2',
                child: []
            }]
        }];
    }    
}

But it always renders the parent nodes only.
Don't know where I am doing wrong! I am almost blank now. Any suggestion, please...

1
  • 1
    put dir.child instead of directories.child in the second ngFor Commented Jul 28, 2017 at 13:37

2 Answers 2

3

Change this line

<ul class="sub-menu" *ngFor="let file of directories.child">

with

<ul class="sub-menu" *ngFor="let file of dir.child">
Sign up to request clarification or add additional context in comments.

1 Comment

@VigneshwaranMarkandan, Glad to here that ,Will you please also accept the answer ?
2

The problem is in your second loop in html, You iterate through directories. You have to iterate through the parent like this

<ul class="sub-menu" *ngFor="let file of dir.child">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.