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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay