Struggling to retrieve the list of sibling nodes for a specific Angular Material tree node within a nested tree structure.
After exploring the Angular Material official documentation, particularly experimenting with the "Tree with nested nodes," I found that neither the NestedTreeControl
nor the SelectionModel
available through @angular/cdk/collections
offer a direct way to access or visualize the sibling nodes of a given node. It's also challenging to determine the level of the NESTED tree where a node is located unless using the flat tree implementation.
Below is the HTML snippet:
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl" class="example-tree">
<!-- Tree node template for leaf nodes -->
<mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>
<li class="mat-tree-node">
<button mat-icon-button disabled></button>
{{node.name}}
</li>
</mat-tree-node>
<!-- Tree node template for expandable nodes -->
<mat-nested-tree-node *matTreeNodeDef="let node; when: hasChild">
<li>
<div class="mat-tree-node">
<button mat-icon-button matTreeNodeToggle
[attr.aria-label]="'toggle ' + node.name">
<mat-icon class="mat-icon-rtl-mirror">
{{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.name}}
</div>
<ul [class.example-tree-invisible]="!treeControl.isExpanded(node)">
<ng-container matTreeNodeOutlet></ng-container>
</ul>
</li>
</mat-nested-tree-node>
</mat-tree>
Here is the accompanying class code:
import {NestedTreeControl} from '@angular/cdk/tree';
import {Component} from '@angular/core';
import {MatTreeNestedDataSource} from '@angular/material/tree';
// Food data structure with nesting
interface FoodNode {
name: string;
children?: FoodNode[];
}
const TREE_DATA: FoodNode[] = [
{
name: 'Fruit',
children: [
{name: 'Apple'},
{name: 'Banana'},
{name: 'Fruit loops'},
]
}, {
name: 'Vegetables',
children: [
{
name: 'Green',
children: [
{name: 'Broccoli'},
{name: 'Brussel sprouts'},
]
}, {
name: 'Orange',
children: [
{name: 'Pumpkins'},
{name: 'Carrots'},
]
},
]
},
];
// Component definition
@Component({
selector: 'tree-nested-overview-example',
templateUrl: 'tree-nested-overview-example.html',
styleUrls: ['tree-nested-overview-example.css'],
})
export class TreeNestedOverviewExample {
// Creating tree control and data source
treeControl = new NestedTreeControl<FoodNode>(node => node.children);
dataSource = new MatTreeNestedDataSource<FoodNode>();
constructor() {
this.dataSource.data = TREE_DATA;
}
hasChild = (_: number, node: FoodNode) => !!node.children && node.children.length > 0;
}
And some CSS styling:
.example-tree-invisible {
display: none;
}
.example-tree ul,
.example-tree li {
margin-top: 0;
margin-bottom: 0;
list-style-type: none;
}
The main challenge lies in accessing the sibling nodes within the NESTED tree structure and determining the exact level based on the current node being processed.