Search code examples
angulartree

Angular2 tree not expanding by default if the entire tree is changed


I am working on angular2 tree component where initially I am displaying the tree as

var nodes =
[
    {
        name: 'a',
        isExpanded: true,
        children: [
            {
                name: 'b',
                isExpanded: true,
                children: [
                    { name: 'c', }
                ]
            },
        ]
    },
    {
        name: 'b',
        isExpanded: true,
        children: [
            {
                name: 'a',
                children: [
                    { name: 'c' },
                ]
            }
        ]
    }
];

this works absolutely fine and the tree is displayed in expanded on a button click i am changing the entire tree and the new tree looks something like this

 changeTree{
  nodes =
        [
            {
                name: 'new Node a',
                isExpanded: true,
                children: [
                    {
                        name: ' new Node b',
                        isExpanded: true,
                        children: [
                            { name: 'new Node c', }
                        ]
                    },
                ]
            },
            {
                name: 'new Node b',
                isExpanded: true,
                children: [
                    {
                        name: 'new Node a',
                        children: [
                            { name: ' new Node c' },
                        ]
                    }
                ]
            }
        ];

this.tree.treeModel.update(); 
this.tree.treeModel.expandAll();
}

I tried using this.tree.treeModel.update(); this.tree.treeModel.expandAll(); but still the tree is not getting expanded when a new tree is loaded.

Any help would be appreciated.


Solution

  • What you can do is add the updateData event to your tree-root (docs)

    <tree-root #tree [nodes]="nodes" (updateData)="onUpdateData($event)"></tree-root>
    

    This event fires everytime the tree model is updated. Within this event you can call the expandAll method to expand the tree

    // component.ts
    onUpdateData(tree){
        tree.treeModel.expandAll();
    }