2016-12-03 2 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

Как тогда я называю этот компонент из другого компонента? –