如何显示树形结构angular2

时间:2016-12-03 18:18:27

标签: javascript angular

我有这样的对象:

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

任何对象都可以childText知道如何显示它吗?

1 个答案:

答案 0 :(得分:5)

您应该使用自引用组件来执行此操作:

@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;
}

tree-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>
例如,

办事处是您的初始数据。