0

I neeed to replace some data on the tree, then run treemodel.update() and after that select a node. Tree is already rendered at that time. This is my code:

    @ViewChild('resulttree') resulttree: ElementRef;
    
    updateResulttree(id: number) {
        for (let node of this.resultNodes) {
          node.children[0].children = node.children[0].children.filter(childnode => childnode.selected);
          node.children[1].children = node.children[1].children.filter(childnode => childnode.selected);
        }        
    
        this.resulttree.treeModel.update();
    
        setTimeout(() => {
            const someNode = this.resulttree.treeModel.getNodeBy(node => node.data.tree_node_id === id);
              someNode.setActiveAndVisible();
            }, 100); 
}

This workarond with setTimeout works, but it's not good. If the update() Method takes more than 100ms, "someNode" will be undefined.

Any ideas how to make it better?

Angular 10, AngularTreeCompoment 10.0.2 https://angular2-tree.readme.io/docs/getting-started

MARISTobi
  • 1
  • 2

1 Answers1

0

from their code https://github.com/CirclonGroup/angular-tree-component/blob/master/projects/angular-tree-component/src/lib/models/tree.model.ts, calling the update() function will fire the updateData event when done, as long as it's not first update (which it shouldn't be if you already have a rendered tree), you could subscribe to that event before calling update() and select your node in the event handler (don't forget to unsubscribe):

  @action update() {
    // Rebuild tree:
    let virtualRootConfig = {
      id: this.options.rootId,
      virtual: true,
      [this.options.childrenField]: this.nodes
    };

    this.dispose();

    this.virtualRoot = new TreeNode(virtualRootConfig, null, this, 0);

    this.roots = this.virtualRoot.children;

    // Fire event:
    if (this.firstUpdate) {
      if (this.roots) {
        this.firstUpdate = false;
        this._calculateExpandedNodes();
      }
    } else {
      this.fireEvent({ eventName: TREE_EVENTS.updateData });
    }
  }
BlackICE
  • 8,816
  • 3
  • 53
  • 91
  • The problem with this solution is that this event gets also fired in different occasions. From their guide "Triggers after tree model was updated, either by changing the inputs of the tree (nodes, options, etc.) or a direct call to update()." I only want to select the node after the direct call of update(). – MARISTobi Jan 18 '21 at 11:09
  • if you subscribe to the event right before you call update, then unsubscribe when the event has been called I would think this will do what you need. – BlackICE Jan 19 '21 at 16:01
  • Can you provide an example of how to correctly subscribe to the event? I've tried several suggestions, but nothing seems to work. My variable "resulttree" is a ViewChild of the tree. – MARISTobi Jan 21 '21 at 13:10