How to save mat tree expansion model and apply it?

Viewed 681

I need to save current expanded nodes of mat tree close all and then expand them all again. My approach was like this:

Save the expansion model

treeControl = new NestedTreeControl<NavbarNode>((node: NavbarNode) => return node.children);

 this.prevExpansionModel = this.treeControl.expansionModel.selected;
      this.treeControl.collapseAll();

and then apply it

this.prevExpansionModel.forEach(object => this.treeControl.expand(object));

It works when I do it this way but the nodes that got expanded will no longer work and I can't toggle them. (I cannot toggle those that have been expanded, other ones I can expand and work normally)

1 Answers

Create a previous expansion model var where you will save the expansion model.

public prevExpansionModel: NavbarNode[] = [];

If the navbar is open save the expansion model, close all node and close the navbar. If it's open then open sidenav and apply the expansion model.

private toggleMatTree() {
    if (this.navbarStatus === NavbarStatus.OPEN) {
      this.prevExpansionModel = this.treeControl.expansionModel.selected;
      this.treeControl.collapseAll();
    } else {
      this.treeControl.collapseAll();
      this.prevExpansionModel.forEach(object => this.treeControl.expand(object));
    }
 }

Here is my logic for opening the sidenav, maybe it will help you.

public toggleSideNav() {
    if (this.navbarStatus === NavbarStatus.OPEN) {
      this.toggleMatTree();
      this.navbarStatus = NavbarStatus.CLOSED;
    } else {
      this.toggleMatTree();
      this.navbarStatus = NavbarStatus.OPEN;
    }
    return this.navbarStatus;
  }
Related