Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get node siblings in an Angular Material nested tree?

I'm trying to fetch the list of sibling nodes for a given Angular Material tree node in a nested tree.

I'm going through Angular Material official docs, and specifically dabbling with the "Tree with nested nodes". Neither NestedTreeControl nor the SelectionModel I was able to get to via @angular/cdk/collections provide ways to access or even see the sibling nodes for a given node. They don't even offer a way to know on what level of the NESTED tree you're node is, unless you're using the flat tree.

Here's the HTML

<mat-tree [dataSource]="dataSource" [treeControl]="treeControl" class="example-tree">
  <!-- This is the tree node template for leaf nodes -->
  <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>
    <li class="mat-tree-node">
      <!-- use a disabled button to provide padding for tree leaf -->
      <button mat-icon-button disabled></button>
      {{node.name}}
    </li>
  </mat-tree-node>
  <!-- This is the 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>

This is the class code

import {NestedTreeControl} from '@angular/cdk/tree';
import {Component} from '@angular/core';
import {MatTreeNestedDataSource} from '@angular/material/tree';

/**
 * Food data with nested structure.
 * Each node has a name and an optiona list of children.
 */
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'},
        ]
      },
    ]
  },
];

/**
 * @title Tree with nested nodes
 */
@Component({
  selector: 'tree-nested-overview-example',
  templateUrl: 'tree-nested-overview-example.html',
  styleUrls: ['tree-nested-overview-example.css'],
})
export class TreeNestedOverviewExample {
  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

.example-tree-invisible {
  display: none;
}

.example-tree ul,
.example-tree li {
  margin-top: 0;
  margin-bottom: 0;
  list-style-type: none;
}

I just need a way to access the sibling nodes. I also really need to know what level I'm on based on the node I'm at when I'm using the NESTED tree.

like image 940
Malik M Avatar asked Dec 06 '25 04:12

Malik M


1 Answers

For anyone looking for an answer on this, I solved my problem as follows.

  1. First create custom data attributes for the node class. This is my node class now:

import {NestedTreeControl} from '@angular/cdk/tree';
import {Component} from '@angular/core';
import {MatTreeNestedDataSource} from '@angular/material/tree';

/**
 * Food data with nested structure.
 * Each node has a name and an optional list of children.
 */
interface FoodNode {
  name: string;
  children?: FoodNode[];
}

export class FoodNode {
  children: BehaviorSubject<FoodNode[]>;
  constructor(
    public name: string,
    public type: string,
    public id: number,
    children?: FoodNode[],
    public parent?: FoodNode,
    public level = 0
  ) {
    this.children = new BehaviorSubject(children === undefined ? [] : children);
  }
}

  1. Second the nested tree class goes as follows
import { NestedTreeControl } from '@angular/cdk/tree';

export class NestedTreeComponent implements OnInit, OnDestroy {
  // TREE CONTROLS
  treeControl: NestedTreeControl<FoodNode>;
  foodTreeLevels = [];
  treeDepth = 1; // initialize tree with default depth 1

  ngOnInit() {
   // initialize tree controls and data source
   this.treeControl = new NestedTreeControl<FoodNode>(this.getChildren);
  }

  /** Get node children */
  getChildren = (node: FoodNode): Observable<FoodNode[]> => node.children;

  /**
   * @desc Add the node to its parent's children object
   */
  addNewFood(parent: FoodNode, foodName: string, foodType: string, foodId: number) {
    // Add the food to the list of children
    const child = new FoodNode(foodName, foodType, foodId, [], parent, 0);
    child.level = parent.level + 1;
    // add a new level to the tree if the parent of this node has no children yet
    if (parent && parent.children.value.length === 0 && !this.foodTreeLevels.includes(child.level)) {
      this.foodTreeLevels.push(child.level);
      this.treeDepth += 1;
    }
    // update the parents' children with this newly added node if the parent exists
    if (parent) {
      const children = parent.children.value;
      children.push(child);
      parent.children.next(children);
   }

  }
  1. Now wherever you need to access the siblings of any node in the tree, you simply go to the nodes parent and then get all of its children as follows:
// This is a node of type FoodNode
const parent = theNodeINeedToGetSiblingsFor.parent; 
const siblings = parent.children.value;
like image 69
Malik M Avatar answered Dec 08 '25 18:12

Malik M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!