Tree State
2 way binding to state
You can control the tree state using 2 way binding.
The state includes the following:
- expandedNodeIds - dictionary of node IDs to booleans
- activeNodeIds - dictionary of node IDs to booleans
- hiddenNodeIds - dictionary of node IDs to booleans
- focusedNodeId - node ID
You can change the state reference and the tree will respond automatically, and also access the tree state at any time, as it is always updated via the 2-way binding.
Example:
<tree-root [(state)]="state" [nodes]="nodes"></tree-root>
import { ITreeState } from 'angular-tree-component';
class MyComponent {
state:ITreeState;
collapseAll() {
this.state = {
...this.state,
expandedNodeIds: {}
};
}
hideFolders() {
const hiddenNodeIds = {};
this.nodes.forEach((node) => {
if (node.data.isFolder) {
hiddenNodeIds[node.id] = true;
}
});
this.state = {
...this.state,
hiddenNodeIds
};
}
}
Persist state to localstorage
This example is using the 2 way binding to tree state to auto save & restore from localstorage:
<tree-root
[state]="state"
(stateChange)="setState($event)"
[nodes]="nodes">
</tree-root>
class MyComponent {
state = localStorage.treeState && JSON.parse(localStorage.treeState);
setState(state) {
localStorage.treeState = JSON.stringify(state);
}
}
Using API
Alternatively, you can use getState
, setState
and subscribe
on treeModel API.
subscribe
will callback a function every time state changes.
<tree-root
#tree
(initialize)="onInit(tree)"
[nodes]="nodes">
</tree-root>
class MyComponent {
onInit(tree) {
if (localStorage.treeState) {
tree.treeModel.setState(JSON.parse(localStorage.treeState);
}
tree.treeModel.subscribe((state) => {
localStorage.treeState = JSON.stringify(state);
});
}
}
Updated less than a minute ago