how to initialize primeng tree component

痴心易碎 提交于 2020-01-01 01:24:46

问题


Given a tree how to initialize it in such way that the nodes are expanded at will?

I already tried to get a reference with @ViewChildren(Tree) tree but is resulting in undefined references when trying to access his children


回答1:


This is a hack that basically simulates clicks along the tree. I add this solution but I really hope someone could find something better.

Given a component with a tree we can get a reference to the treenodes and then "click" them as necessary:

@Component({
    selector: 'filemanager',
    templateUrl: './filemanager.html',
    directives: [Tree]
})
export class FileManagerComponent implements AfterViewInit {

    constructor(private renderer:Renderer) {}    

    ngAfterViewInit() {
        setTimeout(() => { // a timeout is necessary otherwise won't find the elements

            // get the first "p-tree" tag and find his first "toggler"
            let element = document.getElementsByTagName("p-tree")[0].getElementsByClassName("ui-tree-toggler fa fa-fw fa-caret-right")[0];

            //"click" the toggler using the angular2 renderer 
            let event = new MouseEvent('click', {bubbles: true});
            this.renderer.invokeElementMethod(element, 'dispatchEvent', [event]);
        }, 200);
    }

    // more methods and state...   
}

In case you need to initialize deeper nodes in the tree you will need to nest setTimeout functions.




回答2:


You can handle this with a function that put all the expanded attributes to true.

expandAll(toggle: boolean) {
  this.tree.map(node => {
    node.expanded = toggle;
  });
}

ngOnInit() {
  setTimeout(()=>{
    this.expandAll(true);
  }, 0);

}



回答3:


For initialize your tree component expanded you only need set in you json format the property expanded as true.

Sample:

{
    "data": 
    [
        {
            "label": "Pictures",
            "data": "Pictures Folder",
            "expandedIcon": "fa-folder-open",
            "collapsedIcon": "fa-folder",
            "expanded": true, // this flag shoud be true
            "children": [
                {"label": "barcelona.jpg", "icon": "fa-file-image-o", "data": "Barcelona Photo"},
                {"label": "logo.jpg", "icon": "fa-file-image-o", "data": "PrimeFaces Logo"},
                {"label": "primeui.png", "icon": "fa-file-image-o", "data": "PrimeUI Logo"}]
        },
    ]
}


来源:https://stackoverflow.com/questions/38285593/how-to-initialize-primeng-tree-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!