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

Nguyễn Hữu Hiếu - Dec 21 '21 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player