0
votes

Child nodes appear in every parent nodes. Expected result is that child nodes will appear on a specific parent node. There is also an instance where a children node has a children node again.

We were advised not to use a library for this one because before, we used ngx tree view but when we use it, we encounter difficulty in filtering the tree view content when we use other search text box.

First thing I did is to use FOR loop for the parent nodes. I use IF condition to compare if this parent node has a children(in array of objects). If the IF condition satisfied, this child nodes will be push into an array for THAT SPECIFIC PARENT NODE and also return a boolean variable that will be used in *ngIf.

The data passed by this.service.Hierarchy(); is

[{text: "Parent1", value: 1, children: Array(5), checked: false},

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

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

{text: "Parent4", value: 1, children: Array(0), checked: 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); 
    }     
  }
}}

at .html file

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

Expected result:

  • Parent 1

    Child 1(child of parent 1)

    Child 2 (child of parent 1)

    ` * Child Child 1 (children of children 2)

  • Parent 2

  • Parent 3

Actual result:

  • Parent 1

    Child 1(child of parent 1)

    Child 2 (child of parent 1)

  • Parent 2

    Child 1(child of parent 1)

    Child 2 (child of parent 1)

  • Parent 3

    Child 1(child of parent 1)

    Child 2 (child of parent 1)

1
do you mean *ngFor="let child of children"??Saksham
@Saksham, nope. I used child of child (this is where I push the children)Edward

1 Answers

0
votes

you can simply iterate over the child array in the template, if you need support for endless nesting, you can use 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>