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.

James Z
  • 12,209
  • 10
  • 24
  • 44
Sathish
  • 149
  • 2
  • 19

1 Answers1

3

To render flat data as a hierarchy you can use component recursion. Each node will render all its children, which will render the next level of children, etc.

Because there are multiple root nodes, start by having the container component render each top-level item:

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

Then each of those components will render any child nodes using the same component. Because the data is flat, we pass all the list items to each tree component and let that component sort out which items to render.

@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>

Representing the hierarchy is then a matter of styling, such as using padding to indent each level.

Also, if your data changes after the initial render you may want to use the *ngFor trackBy to reduce the required DOM changes.

Demo StackBlitz

Taylor G
  • 846
  • 9
  • 13
  • thanks for the reply ..but i want draw the graph to represent the parent and children ..is this possible to draw the graph between parent and child – Sathish Apr 12 '20 at 13:26
  • 1
    You could represent a tree using the material tree component https://material.angular.io/components/tree/overview but for a connected graph something like Swimlane's ngx-graph https://github.com/swimlane/ngx-graph is a solid option, since it has already solved the challenges of laying out connected components. – Taylor G Apr 12 '20 at 20:12