【问题标题】:Get parent of child node in angular material nested tree在角度材料嵌套树中获取子节点的父节点
【发布时间】:2019-09-18 04:21:19
【问题描述】:

我正在使用角度材质树组件。我能够获取所选节点的详细信息。现在,我想要实现的是获取所选节点的父级或整个父级层次结构。你知道我怎样才能做到这一点吗?

我的树在 Angular Material 文档中看起来像这样:

https://stackblitz.com/angular/mrkvpbkolad?file=app%2Ftree-nested-overview-example.ts

【问题讨论】:

  • 你会在哪个时刻“获取所选节点的父节点或整个父层次结构”?
  • @GCSDC 当我单击树中的特定节点时。

标签: angular angular-material treeview angular-material2


【解决方案1】:

如果你想获得整个父层次结构,在点击一个子节点时,我的解决方案是使用递归函数:

onLeafNodeClick(node) {
  const ancestors = getAncestors(this.dataSource.data, node.name);
}

getAncestors(array, name) {
  if (typeof array !== 'undefined') {
    for (let i = 0; i < array.length; i++) {
      if (array[i].name === name) {
        return [array[i]];
      }
      const a = this.getAncestors(array[i].children, name);
      if (a !== null) {
        a.unshift(array[i]);
        return a;
      }
    }
  }
  return null;
}

这将返回一个新数组,在索引0 处具有根项,在索引n-1 处具有已单击的子节点。

工作示例

https://stackblitz.com/edit/angular-r7rxyl-vwdlhy?file=app/tree-nested-overview-example.ts

节点的直接父节点将是:

const directParent = ancestors[ancestors.length - 2];

你可以使用这个数组来显示面包屑(root/child_1/child_2):

let breadcrumbs = '';
ancestors.forEach(ancestor => {
  breadcrumbs += `${ancestor.name}/`;
});

如果你只是想获取父元素的一些属性(例如:父名父id),我的解决方法是处理原始数据 在将其分配给mat-tree 数据源之前。我们可以在每个节点上添加一个新属性parent,它将是一个存储父元素所需属性的对象。

代码将是:

this.dataSource.data = this._processData(TREE_DATA);

_processData(data, parent = null) {
  data.forEach(item => {
    if (parent !== null) {
      item.parent = {name: parent.name};
    } else {
      item.parent = null;
    }
    if (item.children) {
      this._processData(item.children, item);
    }
  });
  return data;
}

数据处理后的叶节点示例:

{
  name: "Apple", 
  parent: {
    name: "Fruit"
  }
}

工作示例

https://stackblitz.com/edit/angular-r7rxyl?file=app%2Ftree-nested-overview-example.ts

【讨论】:

  • 这太棒了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多