Reputation: 93
I'm working with angular material tree component. I am able to get details of my selected node. Now, what I want to achieve is to get the parent of the selected node or whole parent hierarchy. Do you know how can I achive this?
My tree looks like this in angular material docs:
https://stackblitz.com/angular/mrkvpbkolad?file=app%2Ftree-nested-overview-example.ts
Upvotes: 8
Views: 11219
Reputation: 8461
If you want to get the whole parent hierarchy, at click on a child node, my solution is to use a recursive function:
onLeafNodeClick(node) {
const ancestors = getAncestors(this.dataSource.data, node.name);
}
getAncestors(array, name) {
if (typeof array !== 'undefined') {
for (let i = 0; i < array.length; i++) {
if (array[i].name === name) {
return [array[i]];
}
const a = this.getAncestors(array[i].children, name);
if (a !== null) {
a.unshift(array[i]);
return a;
}
}
}
return null;
}
This will return a new array, having at index 0
the root item, and at index n-1
the child node that has been clicked.
Working example:
https://stackblitz.com/edit/angular-r7rxyl-vwdlhy?file=app/tree-nested-overview-example.ts
The direct parent of the node will be:
const directParent = ancestors[ancestors.length - 2];
You can use this array to display breadcrumbs (root/child_1/child_2
):
let breadcrumbs = '';
ancestors.forEach(ancestor => {
breadcrumbs += `${ancestor.name}/`;
});
If you just want to get some attributes of the parent element (eg: parent name, parent id), my solution is to process the original data before assigning it to mat-tree
data source. We can add a new property on each node, parent
, which will be an object that stores the desired attributes of the parent element.
The code will be:
this.dataSource.data = this._processData(TREE_DATA);
_processData(data, parent = null) {
data.forEach(item => {
if (parent !== null) {
item.parent = {name: parent.name};
} else {
item.parent = null;
}
if (item.children) {
this._processData(item.children, item);
}
});
return data;
}
Example leaf node after data processing:
{
name: "Apple",
parent: {
name: "Fruit"
}
}
Working example:
https://stackblitz.com/edit/angular-r7rxyl?file=app%2Ftree-nested-overview-example.ts
Upvotes: 10