构建树结构Angular 2

时间:2017-07-28 13:32:29

标签: angular typescript recursion treeview

我正在尝试使用带有基本父子概念的角度2来构建树结构。

component.html模板如下所示:

<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文件:

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: []
            }]
        }];
    }    
}

但它总是只渲染父节点 不知道我做错了什么!我现在差不多空白了。有任何建议,请...

2 个答案:

答案 0 :(得分:3)

更改此行

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

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

答案 1 :(得分:2)

问题出在html的第二个循环中,你遍历目录。你必须像这样迭代父母

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