angular-tree-component组件中实现特定节点自动展开

2024-01-03 17:05:56

核心API 都在 expandToNode这个函数中

HTML

treeData的数据结构大概如下

[
    {
        "key": "3293040275",
        "id": "law_category/3293040275",
        "name": "嘿嘿嘿嘿",
        "rank": 0,
        "parentKey": "0",
        "parentName": null,
        "rule": "",
        "data": null,
        "children": [
            {
                "key": "3293069168",
                "id": "law_category/3293069168",
                "name": "哈哈哈哈",
                "rank": 1,
                "parentKey": "3293040275",
                "parentName": null,
                "rule": "",
                "data": null,
                "children": []
            }
        ]
    },
    {
        "key": "3293069383",
        "id": "law_category/3293069383",
        "name": "呵呵呵呵",
        "rank": 0,
        "parentKey": "0",
        "parentName": null,
        "rule": "",
        "data": null,
        "children": []
    }
]
<tree-root
  #tree
  [nodes]="treeData"
  [options]="options"
>
  <ng-template #treeNodeTemplate let-node let-index="index">
    <span>{{ node.data.name }}</span>
  </ng-template>
</tree-root>

JS

getTree是获取树的数据 treeNodeId是要展开节点的Id
setTimeout是为了先让树渲染出来 然后再进行节点选择

import { ViewChild } from "@angular/core";
import { TreeComponent } from "@circlon/angular-tree-component";

@ViewChild("tree") tree: TreeComponent;

options = {
  displayField: "nodeName",
  // isExpandedField: "expanded",
  // idField: "uuid",
  hasChildrenField: "nodes",
  // actionMapping: {
  //   mouse: {
  //     dblClick: (tree, node, $event) => {
  //   		if (node.hasChildren) TREE_ACTIONS.TOGGLE_EXPANDED(tree, node, $event);
  // 		}
  //   },
  //   keys: {
  //     [KEYS.ENTER]: (tree, node, $event) => {
  //       node.expandAll();
  //     }
  //   }
  // },
  allowDrag: (node) => {
    return true;
  },
  allowDrop: (node) => {
    return true;
  },
  allowDragoverStyling: true,
  levelPadding: 10,
  useVirtualScroll: true,
  animateExpand: true,
  scrollOnActivate: true,
  animateSpeed: 30,
  animateAcceleration: 1.2,
  scrollContainer: document.documentElement, // HTML
};

 // 获取树结构 getTree是获取树的数据  treeNodeId是要展开节点的Id
 this.LawsService.getTRee().subscribe((data) => {
   this.treeData = data?.data;
   console.log(this.treeData);
   setTimeout(() => {
     this.expandToNode(treeNodeId);
   }, 0);
 });
expandToNode(nodeId: string) {
  const treeModel = this.tree.treeModel;
  const targetNode = treeModel.getNodeById(nodeId);
  if (targetNode) {
    targetNode.ensureVisible();
    treeModel.setActiveNode(targetNode, { noEvent: true, noFocus: true });
  }
}

文章来源:https://blog.csdn.net/xinbaiyu/article/details/135365053
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。