【问题标题】:How to display tree structure angular2如何显示树结构angular2
【发布时间】:2017-04-18 11:22:34
【问题描述】:

我有这样的对象:

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

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

【问题讨论】:

标签: javascript angular


【解决方案1】:

您应该使用自引用组件来做到这一点:

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

Offices 是您的初始数据。

【讨论】:

  • tree-view.component.html 里面是什么?
  • @VladimirDjukic 看看我回答的 Html 部分。
  • 我如何从其他组件调用该组件?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-04
  • 2011-01-07
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
相关资源
最近更新 更多