DEV Community

Nguyễn Hữu Hiếu
Nguyễn Hữu Hiếu

Posted on • Edited on

angular material tree: fix auto collapse tree each time data updated

Problem

  • Each time angular material tree refresh or update data source => tree auto collapse all row

Solution

  • Save tree expanded state before update data
  expandedNodeSet = new Set<any>();

  private saveExpandedNode(): void {
    const mExpandedNode =
      this.treeControl?.dataNodes
        ?.filter((node) => {
          return this.treeControl.isExpanded(node);
        })
        .map((node) => node.id) || [];
    this.expandedNodeSet = new Set(mExpandedNode);
  }

  private restoreExpandedNode(): void {
    this.treeControl.dataNodes.forEach((node) => {
      const id = node.id;
      const result = this.expandedNodeSet.has(id);
      if (result) {
        this.treeControl.expand(node);
      }
    });
  }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)