2016-12-03 169 views
0

我有對象somethig這樣的:如何顯示樹狀結構angular2

{ 
id: 1, 
text: "Main", 
childText: [ 
    { 
    id: 3, 
    text: "Child 1", 
    childText: [ 
     { 
     id: 5, 
     text: "child 2" 
     childText: [ 
     .... 
     ] 
     } 
    ] 
    } 
]  
} 

任何對象都可以有childText任何想法如何顯示呢?

+0

http://stackoverflow.com/questions/38821475/recursive-component-loading-with-recursive-array/38822751#38822751,http://stackoverflow.com/questions/37746516/use-component-in-itself/37747022#37747022,http://stackoverflow.com/questions/35707464/inject-parent-component-of-the-same-type-as-child-component/35707578#35707578 –

回答

2

你應該使用自參照組件做到這一點:

@Component({ 
    selector: 'app-tree-view', 
    templateUrl: './tree-view.component.html', 
    styleUrls: ['./tree-view.component.css'] 
}) 
export class TreeViewComponent implements OnInit { 
    @Input() data: {children: Array<any>,name: string,id: number}; 
    showChildren: boolean; 
} 

樹view.component.html

<ul class="office-list-unstyled" *ngIf="data"> 
    <li [ngClass]="{'office-parent': d.children.length && !showChildren,'office-child': d.children.length && showChildren}" 
    *ngFor="let d of data.children"> 
    <span (click)="toggleOffices(d)">{{d.name}}</span> 
    <app-tree-view *ngIf="d.children.length && showChildren" [data]="d"></app-tree-view> 
    </li> 
</ul> 

需要注意的是,* ngIf的觀點是停止循環的事情。 然後你就可以在另一個組件使用它:

<app-tree-view [data]="offices"></app-tree-view> 

辦事處是您例如初始數據。

+0

什麼是內部'tree-view.component .html'? –

+0

@VladimirDjukic看看我的答案的Html部分。 –

+0

然後我怎麼從其他組件調用該組件? –