如何初始化primeng树组件

时间:2016-07-09 19:31:47

标签: dom angular primeng

给定tree如何以节点随意扩展的方式初始化它?

我已尝试使用@ViewChildren(Tree) tree获取引用,但在尝试访问其子女时会导致undefined引用

3 个答案:

答案 0 :(得分:3)

这是一个基本上模拟树上点击的黑客。我添加了这个解决方案,但我真的希望有人能找到更好的东西。

给定一个tree的组件,我们可以获得对treenodes的引用,然后"点击"他们视需要:

@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...   
}

如果您需要在树中初始化更深的节点,则需要嵌套setTimeout个函数。

答案 1 :(得分:1)

您可以使用将所有展开的属性设置为true的函数来处理此问题。

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

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

}

答案 2 :(得分:0)

为了初始化扩展的树组件,只需要在json格式中设置扩展为true的属性。

样品:

{
    "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"}]
        },
    ]
}