filipduarte
filipduarte

Reputation: 31

PrimeNG Treetable programmatically expand all nodes not working

I'm trying to recursively expand all nodes on a Primeng TreeTable component but without success. The row icons change and nothing more happens, except when i manualy click on the expand/colapse icon and all nodes are expanded/collapsed accordingly.

Here a stackbliz link for what i'm trying to do, Stackblitz code

And this are my expand/colapse methods:

public expandAll(): void {
    this.files1.forEach(node => {
        this.expandCollapseRecursive(node, true);
    });
}

public collapseAll(): void {
    this.files1.forEach(node => {
        this.expandCollapseRecursive(node, false);
    });
}

private expandCollapseRecursive(node: TreeNode, isExpand: boolean): void {
    node.expanded = isExpand;
    if (node.children) {
        node.children.forEach(childNode => {
            this.expandCollapseRecursive(childNode, isExpand);
        });
    }
}

Upvotes: 2

Views: 3781

Answers (2)

Đinh Luận
Đinh Luận

Reputation: 31

I used the following solution, it helps to keep the state of checkboxes by simulating click events on the TreeTableToggler:

    private fillExpanded(v: TreeNode[], value: boolean){
        for(let it of v){
            it.expanded = value;
            if(it.children){
                this.fillExpanded(it.children, value);
            }
        }
    }

    private simulateClickOn(query: string){
        let v = this.ref.nativeElement.querySelectorAll(query);
        v.forEach(i=>{
            (i as HTMLElement).click();
        });
    }

    expandAll(){
        for(let x of this.renderData){
            if(x.children){
                this.fillExpanded(x.children, true);
            }
        }
        this.simulateClickOn('i.pi-chevron-right');
    }

    collapseAll(){
        this.simulateClickOn('i.pi-chevron-down');
    }

Upvotes: 0

filipduarte
filipduarte

Reputation: 31

I found a solution that works for me using Lodash cloneDeep, making a deep clone from the TreeNode array then doing all the changes in the cloned one before overwriting the "this.files1" property, then everything works.

public expandAll(): void {
    const temp = cloneDeep(this.files1);
    temp.forEach(node => {
        this.expandCollapseRecursive(node, true);
    });
    this.files1 = temp;
}

public collapseAll(): void {
    const temp = cloneDeep(this.files1);
    temp.forEach(node => {
        this.expandCollapseRecursive(node, false);
    });
    this.files1 = temp;
}

private expandCollapseRecursive(node: TreeNode, isExpand: boolean): void {
    node.expanded = isExpand;
    if (node.children) {
        node.children.forEach(childNode => {
            this.expandCollapseRecursive(childNode, isExpand);
        });
    }
}

But is there a better answer?

Upvotes: 1

Related Questions