从树中删除选定的节点
Posted
技术标签:
【中文标题】从树中删除选定的节点【英文标题】:Remove selected node from Tree 【发布时间】:2017-06-01 06:09:56 【问题描述】:我正在使用 angular-tree-component (https://angular2-tree.readme.io) 在 Angular2 应用程序中显示一棵树。
我需要让用户能够选择树中的任何节点并将其删除。这应该删除选定的节点及其所有子节点(如果它是叶节点,则只是节点)。当用户完成后,修剪的树将被发送到服务器并保存在那里。
在下面的示例中,用户选择“节点 1-2”并单击删除。这会从视图中删除“节点 1-2”、“节点 1”和“节点 2”,并更新底层 javascript 对象。然后,用户可以单击另一个按钮(例如,保存)将更新的对象保存在服务器上。
为了实现这一点,我编写了以下代码,该代码在单击删除按钮时调用。我存储所选节点的 id,然后遍历整个树以找到该 id。当 id 匹配时,我使用 'delete' 关键字删除 'id' 和 'text'。但是,“删除子项”不起作用。
deleteSelectedNode()
//Get the node which was selected by the user
let nodeToDelete: TreeNode = this.myService.getActiveNode();
//id will be unique, can be used to identify the node
let idToDelete = nodeToDelete.data.id;
this.traverseTree(this.nodes[0], idToDelete);
traverseTree(obj, idToDelete: string)
for (var k in obj)
if (typeof obj[k] == "object" && obj[k] !== null)
this.traverseTree(obj[k], idToDelete);
else
if (k === 'id')
let id = obj[k];
if (id === idToDelete)
console.log('ID Matched ' + id);
delete obj['id'];
delete obj['text'];
delete obj['children'];
break;
下面是渲染树的 JSON。
"children": [
"children": [
"text": "Node 1",
"id": "A493"
,
"text": "Node 2",
"id": "A494"
],
"text": "Node 1-2",
"id": "A491"
,
"children": [
"children": [
"text": "Node 3",
"id": "A5ab"
,
"text": "Node 4",
"id": "A5ac"
,
"text": "Node 5",
"id": "A5ad"
,
"text": "Node 6",
"id": "A5ae"
,
"text": "Node 7",
"id": "A5af"
,
"text": "Node 8",
"id": "A5b0"
,
"text": "Node 9",
"id": "A5b1"
,
"text": "Node 10",
"id": "A5b2"
,
"text": "Node 11",
"id": "A5b3"
,
"text": "Node 12",
"id": "A5b4"
,
"text": "Node 13",
"id": "A6da"
,
"text": "Node 14",
"id": "A6db"
],
"text": "Node 1-14",
"id": "A495"
,
"children": [
"text": "Node 15",
"id": "A6dc"
,
"text": "Node 16",
"id": "A6dd"
,
"text": "Node 17",
"id": "A6de"
,
"text": "Node 18",
"id": "A6df"
,
"text": "Node 19",
"id": "A6e0"
,
"text": "Node 20",
"id": "A6e1"
,
"text": "Node 21",
"id": "A6e2"
,
"text": "Node 22",
"id": "A6e3"
],
"text": "Node 15-22",
"id": "A496"
,
"text": "Node 23",
"id": "A497"
,
"text": "Node 24",
"id": "A498"
],
"text": "Node 23-24",
"id": "A492"
],
"text": "Node 1-24",
"id": "A490"
如何删除整个节点,包括子节点?另外,有没有更好的方法来做到这一点?
【问题讨论】:
【参考方案1】:您可以通过父母参考轻松做到这一点
deleteNode()
let nodeToDelete: TreeNode = this.tree.treeModel.getActiveNode();
if (nodeToDelete.level === 1)
this.nodes = this.nodes.filter((n) => n.id !== nodeToDelete.id);
else
nodeToDelete.parent.children = nodeToDelete.parent.children.filter((n) => n.id !== nodeToDelete.id);
【讨论】:
以上是关于从树中删除选定的节点的主要内容,如果未能解决你的问题,请参考以下文章