如何使用 Angular 从平面数组创建树

how to create tree from flat array using in Angular

我需要使用 Angular 从平面数据数组中显示一棵树,并且我愿意使用任何包来渲染树。作为用户,我应该能够点击一个节点并找出节点 ID 和标题等详细信息。树应该在加载时展开,但用户应该能够根据需要折叠 parent 节点。我的节点数据模型如下所示:

export class Node {
    nodeID: number;
    title: string;
    parentNodeID: number;
}

我的数据是这样的:

public Nodes: Node[] = [
    {
        nodeID: 1;
        title: parent1;
        parentNodeID: null;
    },
    {
        nodeID: 2;
        title: child1;
        parentNodeID: 1;
    },
    {
        nodeID: 3;
        title: child2;
        parentNodeID: 1;
    }
]

有很多包可以完成这项工作,例如 This one。我没有尝试过,但似乎很容易使用。如果可以,请更改数组中的键。否则,只需将您的项目映射到另一个数组中,例如:

const newArray = array.map(item =>({
      id: item.nodeID,
      name: item.title,
      children: array.filter(el => el.parentNodeID === parentId), // Not sure about that, but this is the idea
    })
  );

newArray 将是提供给你们三个的数据。

你需要一个递归算法,它看起来循环遍历你的平面数组并将 parentNodeID 映射到 Node 以生成树结构,然后使用树组件,例如 angular-tree-component 来渲染你的树。 我在 stackblitz 上做了一个演示。看一看,让我知道是否有帮助。 https://stackblitz.com/github/ramin-ahmadi/Flat-Tree