Tree Utilities
Overview
These are core utility functions for working with the tree structure.
They make it easier to manipulate TreeItem objects (e.g., inserting, removing, or finding nodes).
All utilities are exported from the utils folder and can be imported directly:
import { remove, insertBefore, insertAfter, insertChild, find, getPathToItem, hasChildren, parentDropZone } from 'ngx-builder-dnd';
parentDropZone
export const parentDropZone = '__root__';
The special identifier used by the dropzone directive to represent the root container.
When passed as targetId, functions such as insertAfter will treat the root as the drop target.
remove
export const remove = <T extends TreeItem>(data: T[], id: string): T[] => { ... };
Removes a node (and its children) from a list of TreeItem.
It recursively searches through the tree and filters out the matching id.
insertBefore
export const insertBefore = <T extends TreeItem>(data: T[], targetId: string, newItem: T): T[] => { ... };
Inserts a new TreeItem before the item with the given targetId.
If the target is nested, the function updates the correct subtree.
- If
targetId === parentDropZone, the new item is appended at the root level.
insertAfter
export const insertAfter = <T extends TreeItem>(data: T[], targetId: string, newItem: T): T[] => { ... };
Inserts a new TreeItem after the item with the given targetId.
- If
targetId === parentDropZone, the new item is appended at the root level.
insertChild
export const insertChild = <T extends TreeItem>(data: T[], targetId: string, newItem: T): T[] => { ... };
Inserts a new TreeItem as a child of the item with the given targetId.
- If the parent item has children, the new child is prepended.
- If the parent has no children, the child array is initialized.
- Automatically marks the parent as
isOpen: true.
find
export const find = <T extends TreeItem<any>>(data: T[], itemId: string): T | undefined => { ... };
Finds a TreeItem by itemId.
Searches the entire tree recursively. Returns undefined if the item is not found.
getPathToItem
export const getPathToItem = <T extends TreeItem>({
current,
targetId,
parentIds = [],
}: {
current: T[];
targetId: string;
parentIds?: string[];
}): string[] | undefined => { ... };
Returns the path of parent IDs leading to the target TreeItem.
- If found, it returns an array of IDs from root → parent chain.
- If not found, returns
undefined.
hasChildren
export const hasChildren = <T extends TreeItem>(item: T): boolean => { ... };
Utility check to determine if a TreeItem has a non-empty children array.
See Also
- Tree State Model - Defines the structure of the builder tree state.
- Tree State Service - Manages the builder tree state and updates.