子节点出现在每个父节点中



子节点出现在每个父节点中。预期的结果是子节点将出现在特定的父节点上。在一个实例中,一个孩子节点再次具有儿童节点。

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

我要做的第一件事是用于父节点的循环。我使用条件来比较此父节点是否有子(在对象数组中(。如果满足IF条件,则该子节点将被推入该特定父节点的数组,并返回将在 *ngif中使用的布尔变量。

this.service.hierarchy((传递的数据;是

{text:" parent2",value:1,孩子:array(0(,检查:false},

{text:" parent3",value:1,儿童:数组(0(,检查:false},

{text:" parent4",value:1,儿童:数组(0(,检查:false},]

at .ts file

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>

预期结果:

  • 父母1

    儿童1(父母1(

    儿童2(父母1(

    ` *儿童1(儿童2(

  • 父母2

  • 父母3

实际结果:

  • 父母1

    儿童1(父母1(

    儿童2(父母1(

  • 父母2

    儿童1(父母1(

    儿童2(父母1(

  • 父母3

    儿童1(父母1(

    儿童2(父母1(

您可以简单地在模板中的子数组中迭代,如果您需要对无尽的嵌套支持,则可以使用递归组件/模板

<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>

最新更新