2

I am new to angular 9. I want show the mat-cards as parent and child with graph. Below is the data

 [
       { "id" : "ajson1", "parent" : "#", "text" : "Simple root node" },
       { "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
       { "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
       { "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" },
    ]

Based on the below picture i have to show the mat-card with graphical view

Is there any npm package available? Or is it possible show like this? i tried with swimlane but i can't.

4

1 回答 1

3

要将平面数据呈现为层次结构,您可以使用组件递归。每个节点将渲染其所有子节点,这将渲染下一级子节点,等等。

因为有多个根节点,所以首先让容器组件渲染每个顶级项目:

get rootNodes(): TreeNode[] {
  return this.nodes.filter(node => node.parent === '#');
}
<app-tree *ngFor="let node of rootNodes"
  [nodes]="nodes"
  [nodeId]="node.id">
</app-tree>

然后,这些组件中的每一个都将使用相同的组件渲染任何子节点。因为数据是扁平的,所以我们将所有列表项传递给每个树组件,并让该组件排序要呈现的项。

@Component({
  selector: 'app-tree',
  ...
})
export class TreeComponent  {
  @Input() nodes: TreeNode[];
  @Input() nodeId: string;

  get childNodes(): TreeNode[] {
    return this.nodes.filter(node => node.parent === this.nodeId);
  }
}
<!-- Render the item itself, e.g. using a mat-card -->
<h1>{{nodeId}}</h1>

<!-- Render each child -->
<app-tree *ngFor="let childNode of childNodes" 
  [nodes]="nodes"
  [nodeId]="childNode.id">
</app-tree>

表示层次结构就是样式问题,例如使用填充来缩进每个级别。

此外,如果您的数据在初始渲染后发生更改,您可能希望使用*ngFor trackBy来减少所需的 DOM 更改。

演示 StackBlitz

于 2020-04-11T20:41:52.877 回答