Skip to main content

Tree State

For advanced usage

This service is mainly for advanced customization. Developers can extend it to override the applyTreeAction method and define custom behavior when a TreeAction is applied.

Overview​

The TreeStateService is the core service that manages the tree state of items and tracks the last action performed. It is used internally by the library to handle drag-and-drop updates, tree modifications, and instruction applications.

Import​

import { DndModule } from 'ngx-builder-dnd';

Selector​

TreeStateService

API Reference​

Observables​

NameDescription
tree$: Observable<TreeState>Emits the current tree state whenever it changes.

Properties​

NameDescription
tree: TreeStateReturns the current value of the tree state.

Methods​

NameParametersReturnsDescription
setListlist: TreeItem[]voidReplaces the current tree state with a new list of TreeItems.
dispatchaction: TreeActionvoidApplies a TreeAction to the tree state.
getMoveTargets{ itemId: string }TreeItem[]Returns all tree items except the one with the given itemId, useful for determining valid drop targets.
getChildrenOfItemitemId: stringTreeItem[]Returns the children of a specific tree item by id. If itemId is empty, returns the root tree data.
applyTreeActiontreeItems: TreeItem[] , treeAction: TreeAction[]TreeItem[]Applies a TreeAction to a list of TreeItems. Overridable for advanced users. Uses the library's utils (insertBefore, insertAfter, insertChild, remove) to modify the tree.

Example​

import { Injectable } from '@angular/core';
import { TreeStateService, TreeItem, TreeAction } from 'ngx-builder-dnd';

@Injectable()
class MyCustomTreeState extends TreeStateService {
protected override applyTreeAction(treeItems: TreeItem[], treeAction: TreeAction): TreeItem[] {
// Add custom handling logic
}
}

// Usage
const treeState = new MyCustomTreeState();
treeState.setList([{ id: '1', children: [] }]);
treeState.dispatch({
type: 'add',
itemId: '2',
targetId: '1',
item: { id: '3', children: [] },
instruction: { operation: 'reorder-after', blocked: false },
});

See Also​