Child 个节点出现在每个 Parent 个节点中

Child nodes Appear in Every Parent Nodes

Child个节点出现在每个parent个节点中。 预期结果是 child 个节点将出现在特定的 parent 个节点上。 还有一个例子,一个children节点又有一个children节点。

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

我做的第一件事是对 parent 节点使用 FOR 循环。我使用 IF 条件来比较此 parent 节点是否具有 children(在 objects 的数组中)。如果 IF 条件满足,这个 child 节点将被推入一个数组,用于特定的 PARENT 节点和 return 一个将在 *ngIf 中使用的布尔变量。

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

[{文本:"Parent1",值:1,children:Array(5),选中:false},

{text: "Parent2", value: 1, children: Array(0), checked: false},

{文本:"Parent3",值:1,children:Array(0),选中:false},

{文本:"Parent4",值:1,children:Array(0),选中:false},]

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

预期结果:

实际结果:

你可以简单地遍历模板中的子数组,如果你需要无限嵌套的支持,你可以使用recursive components/templates

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