<nz-table #expandTable [nzData]="listOfMapData"> <thead> <tr> <th nzWidth="40%">ID</th> <th nzWidth="30%">NAME</th> <th>COUNT</th> </tr> </thead> <tbody> <ng-container *ngFor="let data of expandTable.data"> <ng-container *ngFor="let item of mapOfExpandedData[data.key]"> <tr *ngIf="item.parent && item.parent.expand || !item.parent"> <td [nzIndentSize]="item.level * 20" [nzShowExpand]="!!item.childKey" [(nzExpand)]="item.expand" (nzExpandChange)="collapse(mapOfExpandedData[data.key],item,$event)"> {{item.id}} </td> <td>{{item.keyName}}</td> <td>{{item.count}}</td> </tr> </ng-container> </ng-container> </tbody> </nz-table>
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; class TreeNodeInterface { id: string; key: string; parentId: string; keyName: string; expand: boolean; count: number; childKey?: TreeNodeInterface[]; } @Component({ selector: 'home', templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { listOfMapData = [ { "id": "1-1", "keyName": "root", "key":"root", "count": 2, "childKey": [ { "id": "1-2", "keyName": "key1", "key":"key1", "count": 3, "childKey": [ { "id": "1-3", "keyName": "key2", "key":"key2", "count": 2, "childKey": null } ] } ] }, { "id": "2-1", "keyName": "root2 ", "key":"key3", "count": 2, "childKey": [ { "id": "2-2", "keyName": "key3", "key":"key3", "count": 3, "childKey": null } ] } ]; mapOfExpandedData = {}; constructor( ) { } ngOnInit(): void { this.listOfMapData.forEach(item => { this.mapOfExpandedData[item.key] = this.convertTreeToList(item); }); } collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void { if ($event === false) { if (data.childKey) { data.childKey.forEach(d => { const target = array.find(a => a.key === d.key); console.log(target) target.expand = false; this.collapse(array, target, false); }); } else { return; } } } convertTreeToList(root: object): TreeNodeInterface[] { const stack = []; const array = []; const hashMap = {}; stack.push({ ...root, level: 0, expand: false }); while (stack.length !== 0) { const node = stack.pop(); this.visitNode(node, hashMap, array); if (node.childKey) { for (let i = node.childKey.length - 1; i >= 0; i--) { stack.push({ ...node.childKey[i], level: node.level + 1, expand: false, parent: node }); } } } return array; } visitNode(node: TreeNodeInterface, hashMap: object, array: TreeNodeInterface[]): void { if (!hashMap[node.key]) { hashMap[node.key] = true; array.push(node); } } }