简体   繁体   English

如何显示树结构angular2

[英]How to display tree structure angular2

I have object somethig like this: 我有这样的对象somethig:

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

Any object can have childText any idea how to display this? 任何对象都可以有childText任何想法如何显示呢?

You should use a self-referencing component to do that: 您应该使用一个自引用组件来做到这一点:

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

In tree-view.component.html : 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>

Note that, *ngIf in the view is the thing to stop the loop. 请注意,视图中的* ngIf是停止循环的事情。 And then you can use it in another component: 然后可以在另一个组件中使用它:

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

Offices is your initial data for example. 例如, 办公室是您的初始数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM