首页 > 解决方案 > 子节点出现在每个父节点中

问题描述

子节点出现在每个父节点中。预期结果是子节点将出现在特定的父节点上。还有一个例子,一个子节点又多了一个子节点。

我们被建议不要为此使用库,因为之前我们使用 ngx 树视图,但是当我们使用它时,当我们使用其他搜索文本框时,我们会遇到过滤树视图内容的困难。

我做的第一件事是对父节点使用 FOR 循环。我使用 IF 条件来比较此父节点是否有子节点(在对象数组中)。如果满足 IF 条件,则此子节点将被推送到 THAT SPECIFIC PARENT NODE 的数组中,并返回将在 *ngIf 中使用的布尔变量。

this.service.Hierarchy() 传递的数据;是

[{文本:“Parent1”,值:1,孩子:数组(5),检查:假},

{文本:“Parent2”,值:1,孩子:数组(0),检查:假},

{文本:“Parent3”,值:1,孩子:数组(0),检查:假},

{文本:“Parent4”,值:1,孩子:数组(0),检查:假},]

在 .ts 文件

createTree() {
let hierarchy= this.service.Hierarchy(); //data passed
this.treeComponent = hierarchy; 

for(let i=0; i<this.treeComponent.length; i++){

  //Compare parent if has a children, Example 1 has a children
  if(this.treeComponent[i].children.length != 0 ){ 
    for(var children of this.treeComponent[i].children){

      //use for ngIF
      this.isChildrenAvailable = true;
      this.child.push(children); 
    }     
  }
}}

在 .html 文件

<ul *ngFor="let item of treeComponent">
  <input type="radio">
  {{item.text}}

    <div *ngIf = "isChildrenAvailable">
      <ul *ngFor="let child of child" >
        <input type="radio">
           {{child.text}}
     </ul>
   </div>
 </ul>

预期结果:

实际结果:

标签: angulartypescripttreeviewangular7

解决方案


您可以简单地遍历模板中的子数组,如果您需要支持无限嵌套,您可以使用递归组件/模板

<ul>
  <li *ngFor="let item of treeComponent">
    <input type="radio">{{item.text}}
    <div *ngIf="item.children.length">
      <ul>
        <li *ngFor="let child of item.children">
           <input type="radio">{{child.text}}
        </li>
     </ul>
    </div>
  </li>
</ul>

推荐阅读