I have developed a service with two key functions:
getRootNodes(){}
and
getChildren(node:any){}
The getRootNodes function retrieves the first level of root nodes.
Regarding getChildren(nodes:any), it returns the children, but not just as an array of strings. Instead, it provides an array of objects with a property "isExpandable," which is essential for material-tree to determine if a child node has further children.
The next step involves employing our service in the DinamicDataSource. The toggleNode function must utilize the service. If !expands is the code previously placed under setTimeOut, there is no need for a setTimeOut anymore.
If expand=true, we invoke the service and subscribe to the data. The code that was originally under setTimeOut now resides within the subscription block.
In both cases, it is necessary to call this.dataChange.next(this.data).
toggleNode(node: DynamicFlatNode, expand: boolean) {
const index = this.data.indexOf(node);
if (!expand)
{
let count = 0;
for (let i = index + 1; i < this.data.length
&& this.data[i].level > node.level; i++, count++) {}
this.data.splice(index + 1, count);
this.dataChange.next(this.data);
}
else
{
node.isLoading = true;
this.dataService.getChildren(node.item).subscribe(children=>{
if (!children || index < 0) { // If no children, or cannot find the node, no op
node.isLoading = false;
return;
}
.
.
.
})
}
}
The final modification involves transferring the constructor's functions to ngOnInit in the TreeDynamicExample.
ngOnInit()
{
this.treeControl = new FlatTreeControl<DynamicFlatNode>(this.getLevel, this.isExpandable);
this.dataSource = new DynamicDataSource(this.treeControl, this.dataService);
this.dataService.getRootNodes().subscribe(res=>{
this.dataSource.data = res.map(name => new DynamicFlatNode(name, 0, true));
})
}
Prior to assigning this.dataSourceData to a DynamicFlatNode, obtaining the data and processing it within the subscribe block is crucial.
Update: Demystifying the DynamicDataSource.
.
.
.
I hope this explanation clarifies the functionality behind the dynamic tree. Here is the link to the stackblitz, where I added simple buttons to add a node, add a subnode, and change a node.