基本TreeView的节点打开/关闭逻辑

时间:2017-12-31 06:52:22

标签: angular typescript

所以我正在创建一个基本的TreeView,只是为了列出一个包含组件的目录结构:

MyTreeMenuComponent [TypeScript](家长):

@Component({
  selector: 'mytree-menu',
  template: `<div style="margin-left:30px">
                <mytree [treeItems]="treeItems"> Loading.. </mytree>
                <ng-content></ng-content>
            <div>`,
})

export class MyTreeMenuComponent implements OnInit {
  treeItems: any;
  constructor(private http: Http, @Inject('BASE_URL') private baseUrl: string){}

  ngOnInit() {
    this.fetchFileList(); // function assigns directory listing to `treeItems`
  }
}

MyTreeComponent [TypeScript](儿童):

@Component({
  selector: 'mytree',
  templateUrl: './mytree.component.html',
})

export class MyTreeComponent {
  @Input() treeItems: any;
  constructor(public omni: OmniService) { }
  setSelection(val: any) {
    this.omni.selectedFile = val;
  }
} 

MyTreeComponent [HTML]:

<li *ngFor="let item of treeItems?.children">
  <a (click)="showList = !showList; setSelection(item)">
    {{ item?.name + (item?.isFile ? "" : " [" + item?.size + "]" ) }}
  </a>
  <ul *ngIf="showList">
    <mytree [treeItems]="item"></mytree>
  </ul>
</li>

在HTML文件中,您可以看到它是递归的,这样只要有子节点,就可以继续使用子节点创建树。这是非常基本的,我不想要任何花哨的功能,所以我不会选择任何第三方选项。对于有缺陷的节点打开/关闭逻辑,一切正常之外:

enter image description here

单击节点可打开/关闭其相邻节点。我在这里做错了什么,或者在HTML或TypeScript中可以做些什么,以便只打开/关闭点击的节点?

1 个答案:

答案 0 :(得分:0)

找到了解决方案!

isExpanded界面中添加了布尔item,然后:

MyTreeComponent [HTML]:

<li *ngFor="let item of treeItems?.children">
  <a (click)="setSelection(item)">
     {{ item?.name + (item?.isFile ? "" : " [" + item?.size + "]" ) }}</a>
  <!-- Replace `*ngIf="showList"` with `*ngIf="item.isExpanded"` -->
  <ul *ngIf="item.isExpanded">
     <mytree [treeItems]="item"></mytree>
  </ul>
</li>

MyTreeComponent [TypeScript](儿童):

//codes above
setSelection(val: any) {
    this.omni.selectedFile = val;
    val.isExpanded = !val.isExpanded; //added this
}

现在一切正常如预期。