0
votes

I'm using material tree component.

What i want to do is to save tree state in local storage and retrieve it afterwards.

I serialize data of dataSource in json (JSON.stringify) and deserialize it afterwards

Here is function:

  initTree() {

    const tree_json = localStorage.getItem(this.storage_key)

    if (tree_json != null) {
      const nodes = JSON.parse(tree_json)
      this.dataSource.data = nodes
      this.matTree.renderNodeChanges(nodes)
    } else {
      this.treeSource.getRootNodes().subscribe(nodes => {
          this.dataSource.data = nodes

      })
    }

  }

It looks like it works but not at all.. If i click on expanded node it doesn't collapse, it adds duplicated child. What's correct way to save tree?

I found this, may be i need to call render somehow? https://material.angular.io/components/tree/api#MatTree

1

1 Answers

0
votes

I figured it out

  initTree() {

    const savedTree = this.getSavedTree()

    if (savedTree != null) {
        savedTree.selectedNodes.forEach(node => {
            const nodeStr = JSON.stringify(node)
            const obj = savedTree.nodes.find(node2 => JSON.stringify(node2) == nodeStr)
            if (obj != undefined) {
                this.treeControl.expansionModel.select(obj)
            }
        })
        this.dataSource.data = savedTree.nodes
    } else {
      this.treeSource.getRootNodes().subscribe(nodes => {
          this.dataSource.data = nodes
      })
    }

  }

interface SavedTree {
    timestamp: number
    nodes: tree_node.Node[],
    selectedNodes: tree_node.Node[]
}

function getCurrentSeconds(): number {
    return Date.now().valueOf() * 1000
}