“initialized” event of angular2-tree-component is

2019-07-25 04:35发布

问题:

I am using angular2-tree-component and want to show already expanded tree. Angular docs says to use initialized event for expanding tree after data is come to tree:

Triggers after tree model was created. Good for performing actions immediately on init, like expanding / activating certain nodes, etc. You can access the tree model using a ref, as described in the API section.

But tree is not expanded after rendered:

I am loading data on ngOnInit():

ngOnInit() {
    this.getApiFunction(request, item)
        .subscribe(x => {    
            console.log('before adjusting data');            
            this.adjustDataToTree(x);            
            console.log('after adjusting data');                
        });
}


adjustDataToTree(reports:any[]){        
    //some cycle to handle data for treeView
    for(...){...}
    this.Items.length = 0;
    this.Items = data from above cycle;        
}

code to handle initialized event:

onTreeLoad(){
    //alert('on Tree Load');
    this.tree.treeModel.expandAll();
    console.log('this.tree.treeModel.expandAll() is called!:)');        
}

My tree looks like this:

<tree-root (initialized)="onTreeLoad()" [nodes]="Items"  
    [options]="customTemplateStringOptions" #tree>        
    <ng-template class="expand-tree" #treeNodeTemplate let-node>
        <span (click)="currToggleExpanded(node)" *ngIf="node?.data?.expanded === true" 
            title="{{node.data.subTitle}}">{{ node.data.name }} {{ childrenCount(node) }} 
        </span>
        <span (click)="currToggleExpanded(node)" ngIf="!node?.data?.expanded === true" 
             title="{{node.data.subTitle}}">{{ node.data.name }} {{ childrenCount(node) }}
        </span>
    </ng-template>
</tree-root>

initialized event is fired before data is loaded. It can be seen by order of logs:

So what am I doing wrong or why initialized event is fired before data is loaded into treeview?

回答1:

Try adding an ngIf to your tree so it does not render until the data is ready

<tree-root *ngIf="Items" (initialized)="onTreeLoad($event)" [nodes]="Items"  
...>
    ...
</tree-root>

And also pass in the tree object through your initialized method onTreeLoad($event) and use that passed in value. This part may not necessarily be needed, this.tree should be the same object.

onTreeLoad(tree): void {
    tree.treeModel.expandAll();
}