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
| Name | Description |
|---|---|
tree$: Observable<TreeState> | Emits the current tree state whenever it changes. |
Properties
| Name | Description |
|---|---|
tree: TreeState | Returns the current value of the tree state. |
Methods
| Name | Parameters | Returns | Description |
|---|---|---|---|
setList | list: TreeItem[] | void | Replaces the current tree state with a new list of TreeItems. |
dispatch | action: TreeAction | void | Applies 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. |
getChildrenOfItem | itemId: string | TreeItem[] | Returns the children of a specific tree item by id. If itemId is empty, returns the root tree data. |
applyTreeAction | treeItems: 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
- Tree State Model - Defines the structure of the builder tree state.
- Tree Utils - Provides helper functions for tree operations.