Ennio
Ennio

Reputation: 1157

How to get the id from all children on Angular-tree-component?

I'm using Angular-Tree-Component to display a tree view on my application. But once on a node I need to get the list of all children under that node and their children too.

I saw that they have a function on their documentation doForAll that is invoked for every node under the node I'm in.

https://rawgit.com/500tech/angular-tree-component/master/doc/interfaces/api.itreenode.html#doforall

I can call that function and it works fine when I do a console.log, but when I try to push the ID of my node to my array I only get the first element.

  getChildren(node: TreeNode) {
     node.doForAll((data) => {
         console.log(data.id);
         this.guideArray.push(data.id);
     });
     console.log(this.guideArray);
  }

enter image description here

enter image description here

Upvotes: 1

Views: 4945

Answers (2)

MG K
MG K

Reputation: 23

For anyone else still looking for a way to find get child IDS at all levels synchronously under the parent node, you can use the below function that will get the data all at once synchronously:

getAllChildrenIDs(node: TreeNode) {
 let arraywithIDs: number[] = [];
 if (node.hasChildren) {
  node.children.forEach((node1: TreeNode) => {
    arraywithIDs.push(node1.id);
    console.log('child level: ', node1.level);
    console.log(node1);
    arraywithIDs = arraywithIDs.concat(this.getAllChildrenIDs(node1));
   });
 }
 return arraywithIDs;
}

Upvotes: 0

cyr_x
cyr_x

Reputation: 14257

The problem you're having is that the console.log after you invoked the method isn't aware of the latest array state. That's because the implementation of doForAll is using a Promise, which is asynchronious. So the console.log command doesn't log the latest state.

You could create an BehaviorSubject with the all nodes like this:

getChildren(node: TreeNode) {
     let nodeIds$ = new BehaviorSubject([]);
     node.doForAll((data) => {
         nodeIds$.next(nodeIds$.getValue().concat(data.id));
     });
     return nodeIds$;
}

See: implementation of doForAll

Upvotes: 2

Related Questions