How to programmatically focus to a node in PrimeNG Tree?

Viewed 3191

Using PrimeNG, I can scroll to a TreeNode:

In html:

<p-tree #mytreeid id="mytree"></p-tree>

In Angular:

@ViewChild("mytree") mytree: Tree;
// selection is the TreeNode you want to scroll into view
scrollToSelectionPrimeNgDataTree(selection, tree, elementIdName) {
      if (tree.value !== null) {
          let index = tree.value.indexOf(selection);
              let ele = document.getElementById(elementIdName).querySelectorAll("p-treenode")[index];
              ele.scrollIntoView();
              //ele.focus();
      }
  }

Question: How to make the TreeNode(ie. 'selection') focused? I tried to call the focus() method, but focus() is not the method of the Element.

2 Answers

You must transform your previous data to TreeNode and bind it to the selection property the below would be a good candidate as an example: assume that you have a list of nested categories and you are supposed to select one of them in edit mode:

previouslySelectedParentCategory:TreeNode

initializeForEdit(){
 this.previouslySelectedParentCategory= 
    this.convertCategoryToNode(this.selectedParentCategory)
}


  private convertCategoryToNode(category): TreeNode {
    return {
      key: category.categoryId,
      label: category.name,
      data: category,
    };
  }

HTML file

 <p-tree
        [filter]="true"
        [value]="categoriesNode"
        [scrollHeight]="defaultScrollHeight"
        selectionMode="single"
        [(selection)]="previouslySelectedParentCategory"
        display="chip"
        (onNodeSelect)="handleNodeSelect($event)"
        #parentCategoryTree
      >
        <ng-template p-Template="empty">
          {{ "primeng.emptyMessage" | translate }}
        </ng-template>
      </p-tree>
Related