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