Tree Tree is used to display hierarchical data.

Basic

Loader

Single Selection

Selected Node: {{selectedFile ? selectedFile.label : 'none'}}

Multiple Selection with Metakey

Selected Nodes: {{file.label}}

Multiple Selection with Checkbox

Selected Nodes: {{file.label}}

Lazy Loading

Template

Context Menu

DragDrop

Files

Server 1

Server 2

Programatic Tree Expansion

Horizontal Tree

Selected Node: {{selectedFile3 ? selectedFile3.label : 'none'}}

Import


import {TreeModule} from 'primeng/tree';
import {TreeNode} from 'primeng/api';

Getting Started

Tree component requires an array of TreeNode objects as its value. Let's begin with the TreeNode api. Note that all of the properties are optional.

Name Type Default Description
label string null Label of the node.
data any null Data represented by the node.
icon string null Icon of the node to display next to content.
expandedIcon string null Icon to use in expanded state.
collapsedIcon string null Icon to use in collapsed state.
children TreeNode[] null An array of treenodes as children.
leaf boolean null Specifies if the node has children. Used in lazy loading.
style string null Inline style of the node.
styleClass string null Style class of the node.
expanded boolean null Whether the node is in an expanded or collapsed state.
type string null Type of the node to match ng-template type.
parent TreeNode null Parent of the node.
styleClass string null Name of the style class for the node element.
draggable boolean null Whether to disable dragging for a particular node even if draggableNodes is enabled.
droppable boolean null Whether to disable dropping for a particular node even if droppableNodes is enabled.
selectable boolean null Used to disable selection of a particular node.
emptyMessage string No records found. Text to display when there is no data.

Most of the time, nodes will be loaded from a remote datasoure, here is an example NodeService that fetches the data from a json file.


@Injectable()
export class NodeService {

    constructor(private http: Http) {}

    getFiles() {
        return this.http.get('showcase/resources/data/files.json')
                    .toPromise()
                    .then(res => <TreeNode[]> res.json().data);
    }
}

The files.json file consists of sample data. In a real application, this should be a dynamic response generated from the remote call.


{
    "data":
    [
        {
            "label": "Documents",
            "data": "Documents Folder",
            "expandedIcon": "fa-folder-open",
            "collapsedIcon": "fa-folder",
            "children": [{
                    "label": "Work",
                    "data": "Work Folder",
                    "expandedIcon": "fa-folder-open",
                    "collapsedIcon": "fa-folder",
                    "children": [{"label": "Expenses.doc", "icon": "fa-file-word-o", "data": "Expenses Document"}, {"label": "Resume.doc", "icon": "fa-file-word-o", "data": "Resume Document"}]
                },
                {
                    "label": "Home",
                    "data": "Home Folder",
                    "expandedIcon": "fa-folder-open",
                    "collapsedIcon": "fa-folder",
                    "children": [{"label": "Invoices.txt", "icon": "fa-file-word-o", "data": "Invoices for this month"}]
                }]
        },
        {
            "label": "Pictures",
            "data": "Pictures Folder",
            "expandedIcon": "fa-folder-open",
            "collapsedIcon": "fa-folder",
            "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"}]
        },
        {
            "label": "Movies",
            "data": "Movies Folder",
            "expandedIcon": "fa-folder-open",
            "collapsedIcon": "fa-folder",
            "children": [{
                    "label": "Al Pacino",
                    "data": "Pacino Movies",
                    "children": [{"label": "Scarface", "icon": "fa-file-video-o", "data": "Scarface Movie"}, {"label": "Serpico", "icon": "fa-file-video-o", "data": "Serpico Movie"}]
                },
                {
                    "label": "Robert De Niro",
                    "data": "De Niro Movies",
                    "children": [{"label": "Goodfellas", "icon": "fa-file-video-o", "data": "Goodfellas Movie"}, {"label": "Untouchables", "icon": "fa-file-video-o", "data": "Untouchables Movie"}]
                }]
        }
    ]
}

The component that uses this service makes a call to getFiles() and assigns them back to files property that is bound to the tree.


export class TreeDemoComponent implements OnInit {

    files: TreeNode[];

    constructor(private nodeService: NodeService) {}

    ngOnInit() {
        this.nodeService.getFiles().then(files => this.files = files);
    }

}


<p-tree [value]="files"></p-tree>

Selection

Tree supports 3 selection methods, single, multiple and checkbox. Selection is enabled by setting selectionMode property and providing a single TreeNode or an array of TreeNodes to reference the selections depending on the selection mode.


export class TreeDemoComponent implements OnInit {

    files: TreeNode[];

    selectedFile: TreeNode;

    constructor(private nodeService: NodeService) {}

    ngOnInit() {
        this.nodeService.getFiles().then(files => this.files = files);
    }

}


<p-tree [value]="files" selectionMode="single" [(selection)]="selectedFile"></p-tree>

In multiple mode or checkbox mode, selection property should be an array. In multiple mode, items can either be selected using metaKey or toggled individually depending on the value of metaKeySelection property value which is true by default. On touch enabled devices metaKeySelection is turned off automatically. In checkbox mode, when inititing a tree with preselections, also set partialSelected property on node so that minus icon can be displayed when necessary.


    export class TreeDemoComponent implements OnInit {

        files: TreeNode[];

        selectedFiles: TreeNode[];

        constructor(private nodeService: NodeService) {}

        ngOnInit() {
            this.nodeService.getFiles().then(files => this.files = files);
        }

    }


<p-tree [value]="files" selectionMode="single" [(selection)]="selectedFiles"></p-tree>

In checkbox mode, selections propagate up and down, if you prefer not to do so, propagation can be turned off by propagateSelectionDown and propagateSelectionUp properties.


<p-tree [value]="files" selectionMode="checkbox" [(selection)]="selectedFiles"
                [propagateSelectionUp]="false" [propagateSelectionDown]="false"></p-tree>

Tree provides onNodeSelect and onNodeUnselect options as callbacks for selection feature.


<p-tree [value]="files" selectionMode="single" [(selection)]="selectedFiles" (onNodeSelect)="nodeSelect($event)"></p-tree>


export class TreeDemoComponent implements OnInit {

    files: TreeNode[];

    selectedFiles: TreeNode[];

    constructor(private nodeService: NodeService) {}

    ngOnInit() {
        this.nodeService.getFiles().then(files => this.files = files);
    }

    nodeSelect(event) {
        //event.node = selected node
    }

}

Selection of a particular node can be disabled by setting the selectable property of the node to false.

Icons

Icon of a treenode is defined using the icon property, if you need an icon depending on the expand or collapse state, use expandedIcon and collapsedIcon instead.

Templating

By default label of a treenode is displayed inside a tree node, in case you need to place custom content define a pTemplate that gets the treenode as an implicit variable. Example below places an input field to create editable treenodes.


<p-tree [value]="files">
    <ng-template let-node  pTemplate="default">
        <input [(ngModel)]="node.label" type="text" style="width:100%">
    </ng-template>
</p-tree>

Multiple templates are supported by matching the type property of the TreeNode with the type of pTemplate. If a node has no type, then default ng-template is used.


<p-tree [value]="files">
    <ng-template let-node  pTemplate="picture">
        <img [attrs.src]="picture.path">
    </ng-template>
    <ng-template let-node  pTemplate="default">
        <input [(ngModel)]="node.label" type="text" style="width:100%">
    </ng-template>
</p-tree>

ContextMenu

Tree has exclusive integration with context menu created by binding a menu instance to the tree.


<p-tree [value]="files" selectionMode="single" [(selection)]="selectedFile2" [contextMenu]="cm"></p-tree>

<p-contextMenu #cm [model]="items"></p-contextMenu>

Lazy Loading

Lazy loading is handy to deal with large datasets. Instead of loading the whole tree, nodes can be loaded at onNodeExpand event. Important part of implementing lazy loading is defining leaf property of a node as false, this will instruct tree to display an arrow icon to indicate there are children of this node although they are not loaded yet. When the lazy node is expanded, onNodeExpand is called and a remote call can be made to add the children to the expanded node.


<p-tree [value]="files" (onNodeExpand)="loadNode($event)"></p-tree>


export class TreeDemoComponent implements OnInit {

    files: TreeNode[];

    selectedFiles: TreeNode[];

    constructor(private nodeService: NodeService) {}

    ngOnInit() {
        //initial nodes
        this.nodeService.getFiles().then(files => this.files = files);
    }

    loadNode(event) {
        if(event.node) {
            //in a real application, make a call to a remote url to load children of the current node and add the new nodes as children
            this.nodeService.getLazyFiles().then(nodes => event.node.children = nodes);
        }
    }

}

Assume at ngOnInit tree is initialized with a data like below that has nodes having no actual children but leaf property is set false.


{
    "data":
    [
        {
            "label": "Lazy Node 0",
            "data": "Node 0",
            "expandedIcon": "fa-folder-open",
            "collapsedIcon": "fa-folder",
            "leaf": false
        },
        {
            "label": "Lazy Node 1",
            "data": "Node 1",
            "expandedIcon": "fa-folder-open",
            "collapsedIcon": "fa-folder",
            "leaf": false
        },
        {
            "label": "Lazy Node 1",
            "data": "Node 2",
            "expandedIcon": "fa-folder-open",
            "collapsedIcon": "fa-folder",
            "leaf": false
        }
    ]
}

Drag and Drop

Nodes can be reordered within a tree and also can be transferred between multiple trees. To enable dragging from a tree set draggableNodes to true and to allow dropping enable droppableNodes property. In addition, import TreeDragDropService and configure it as a provider at your component or module.


import {TreeDragDropService} from 'primeng/api';


<p-tree [value]="files" draggableNodes="true" droppableNodes="true"></p-tree>

Multiple trees can be used in a drag drop operation, in order to add constraints like rejecting drags from a certain tree but allow from another use draggableScope and droppableScope properties which can be a string or an array. Following example uses 3 trees where second one only accepts drags from first tree and second one only accepts from second tree whereas first tree accepts drops from 3rd tree.


<p-tree [value]="files" draggableNodes="true" droppableNodes="true" draggableScope="a" droppableScope="c"></p-tree>
<p-tree [value]="files" draggableNodes="true" droppableNodes="true" draggableScope="b" droppableScope="a"></p-tree>
<p-tree [value]="files" draggableNodes="true" droppableNodes="true" draggableScope="c" droppableScope="b"></p-tree>

Loading Status

Tree has a loading property, when enabled a spinner icon is displayed to indicate data load.

An optional loadingIcon property can be passed in case you prefer a different icon.


<p-tree [value]="files" [loading]="loading"></p-tree>

Horizontal Orientation

Horizontal mode is the alternative option for orientation.


<p-tree [value]="files" layout="horizontal"></p-tree>

Properties

Name Type Default Description
value array null An array of treenodes.
selectionMode string null Defines the selection mode, valid values "single", "multiple", and "checkbox".
selection any null A single treenode instance or an array to refer to the selections.
style string null Inline style of the component.
styleClass string null Style class of the component.
contextMenu ContextMenu null Context menu instance.
layout string vertical Defines the orientation of the tree, valid values are 'vertical' and 'horizontal'.
metaKeySelection boolean true Defines how multiple items can be selected, when true metaKey needs to be pressed to select or unselect an item and when set to false selection of each item can be toggled individually. On touch enabled devices, metaKeySelection is turned off automatically.
propagateSelectionUp boolean true Whether checkbox selections propagate to ancestor nodes.
propagateSelectionDown boolean true Whether checkbox selections propagate to descendant nodes.
loading boolean false Displays a loader to indicate data load is in progress.
loadingIcon string fa-circle-o-notch The icon to show while indicating data load is in progress.

Events

Name Parameters Description
onNodeSelect event.originalEvent: browser event
event.node: Selected node instance.
Callback to invoke when a node is selected.
onNodeUnselect event.originalEvent: browser event
event.node: Unselected node instance.
Callback to invoke when a node is unselected.
onNodeExpand event.originalEvent: browser event
event.node: Expanded node instance.
Callback to invoke when a node is expanded.
onNodeCollapse event.originalEvent: browser event
event.node: Collapsed node instance.
Callback to invoke when a node is collapsed.
onNodeContextMenuSelect event.originalEvent: browser event
event.node: Selected node instance.
Callback to invoke when a node is selected with right click.
onNodeDrop event.originalEvent: browser event
event.dragNode: Dragged node instance
event.dropNode: Dropped node instance. event.index: Index of the dropped node within siblings.
Callback to invoke when a node is dropped.

Styling

Following is the list of structural style classes, for theming classes visit theming page.

Name Element
ui-tree Main container element
ui-tree-horizontal Main container element in horizontal mode
ui-tree-container Container of nodes
ui-treenode A treenode element
ui-treenode-content Content of a treenode
ui-treenode-toggler Toggle icon
ui-treenode-icon Icon of a treenode
ui-treenode-label Label of a treenode
ui-treenode-children Container element for node children
ui-treenode-content-selected Content of a selected node.

Dependencies

None.

View on GitHub

<p-growl [value]="msgs"></p-growl>

<h3 class="first">Basic</h3>
<p-tree [value]="filesTree0"></p-tree>

<h3>Loader</h3>
<p-tree [value]="filesTree1" [loading]="loading"></p-tree>

<h3>Single Selection</h3>
<p-tree [value]="filesTree2" selectionMode="single" [(selection)]="selectedFile"
    (onNodeSelect)="nodeSelect($event)" (onNodeUnselect)="nodeUnselect($event)"></p-tree>
<div style="margin-top:8px">Selected Node: {selectedFile ? selectedFile.label : 'none'}</div>

<h3>Multiple Selection with Metakey</h3>
<p-tree [value]="filesTree3" selectionMode="multiple" [(selection)]="selectedFiles"
    (onNodeSelect)="nodeSelect($event)" (onNodeUnselect)="nodeUnselect($event)"></p-tree>
<div>Selected Nodes: <span *ngFor="let file of selectedFiles">{file.label} </span></div>

<h3>Multiple Selection with Checkbox</h3>
<p-tree [value]="filesTree4" selectionMode="checkbox" [(selection)]="selectedFiles2"></p-tree>
<div>Selected Nodes: <span *ngFor="let file of selectedFiles2">{file.label} </span></div>

<h3>Lazy Loading</h3>
<p-tree [value]="lazyFiles" (onNodeExpand)="nodeExpand($event)" [style]="{'max-height':'200px','overflow':'auto'}"></p-tree>

<h3>Template</h3>
<p-tree [value]="filesTree5">
    <ng-template let-node pTemplate="default">
        <input [(ngModel)]="node.label" type="text" style="width:100%">
    </ng-template>
</p-tree>

<h3>Context Menu</h3>
<p-tree [value]="filesTree6" selectionMode="single" [(selection)]="selectedFile2" [contextMenu]="cm"></p-tree>
<p-contextMenu #cm [model]="items"></p-contextMenu>

<h3>DragDrop</h3>
<div class="ui-g ui-fluid">
    <div class="ui-g-12 ui-md-3">
        <h4>Files</h4>
        <p-tree [value]="filesTree7" draggableNodes="true" droppableNodes="true" dragdropScope="files"></p-tree>
    </div>

    <div class="ui-g-12 ui-md-1" style="text-align:center">
        <i class="fa fa-exchange" style="font-size:36px;margin-top: 28px;"></i>
    </div>

    <div class="ui-g-12 ui-md-3">
        <h4>Server 1</h4>
        <p-tree [value]="filesTree8" draggableNodes="true" droppableNodes="true" dragdropScope="files"></p-tree>
    </div>

    <div class="ui-g-12 ui-md-1" style="text-align:center">
        <i class="fa fa-exchange" style="font-size:36px;margin-top: 28px;"></i>
    </div>

    <div class="ui-g-12 ui-md-3">
        <h4>Server 2</h4>
        <p-tree [value]="filesTree9" draggableNodes="true" droppableNodes="true" dragdropScope="other"></p-tree>
    </div>

    <div class="ui-g-12 ui-md-1">

    </div>
</div>

<h3>Programatic Tree Expansion</h3>
<p-tree #expandingTree [value]="filesTree10"></p-tree>
<div style="margin-top: 8px">
    <button pButton type="button" label="Expand all" (click)="expandAll()"></button>
    <button pButton type="button" label="Collapse all" (click)="collapseAll()"></button>
</div>

<h3>Horizontal Tree</h3>
<p-tree [value]="filesTree11" layout="horizontal" selectionMode="single" [(selection)]="selectedFile3" ></p-tree>
<div style="margin-top:8px">Selected Node: {selectedFile3 ? selectedFile3.label : 'none'}</div>


export class TreeDemo implements OnInit {

    msgs: Message[];

    @ViewChild('expandingTree')
    expandingTree: Tree;

    filesTree1: TreeNode[];
    filesTree2: TreeNode[];
    filesTree3: TreeNode[];
    filesTree4: TreeNode[];
    filesTree5: TreeNode[];
    filesTree6: TreeNode[];
    filesTree7: TreeNode[];
    filesTree8: TreeNode[];
    filesTree9: TreeNode[];
    filesTree10: TreeNode[];
    filesTree11: TreeNode[];

    lazyFiles: TreeNode[];

    selectedFile: TreeNode;

    selectedFile2: TreeNode;

    selectedFile3: TreeNode;

    selectedFiles: TreeNode[];

    selectedFiles2: TreeNode[];

    items: MenuItem[];

    loading: boolean;

    constructor(private nodeService: NodeService) { }

    ngOnInit() {
        this.loading = true;
        this.nodeService.getFiles().then(files => this.filesTree0 = files);
        setTimeout(() => {
            this.nodeService.getFiles().then(files => this.filesTree1 = files);
            this.loading = false;
        }, 3000);
        this.nodeService.getFiles().then(files => this.filesTree2 = files);
        this.nodeService.getFiles().then(files => this.filesTree3 = files);
        this.nodeService.getFiles().then(files => this.filesTree4 = files);
        this.nodeService.getFiles().then(files => this.filesTree5 = files);
        this.nodeService.getFiles().then(files => this.filesTree6 = files);
        this.nodeService.getFiles().then(files => this.filesTree7 = files);
        this.filesTree8 = [
            {
                label: "Backup",
                data: "Backup Folder",
                expandedIcon: "fa-folder-open",
                collapsedIcon: "fa-folder"
            }
        ];
        this.filesTree9 = [
            {
                label: "Storage",
                data: "Storage Folder",
                expandedIcon: "fa-folder-open",
                collapsedIcon: "fa-folder"
            }
        ];
        this.nodeService.getFiles().then(files => this.filesTree10 = files);
        this.nodeService.getFiles().then(files => {
            this.filesTree11 = [{
                label: 'Root',
                children: files
            }];
        });

        this.nodeService.getLazyFiles().then(files => this.lazyFiles = files);

        this.items = [
            {label: 'View', icon: 'fa-search', command: (event) => this.viewFile(this.selectedFile2)},
            {label: 'Unselect', icon: 'fa-close', command: (event) => this.unselectFile()}
        ];
    }

    nodeSelect(event) {
        this.msgs = [];
        this.msgs.push({severity: 'info', summary: 'Node Selected', detail: event.node.label});
    }

    nodeUnselect(event) {
        this.msgs = [];
        this.msgs.push({severity: 'info', summary: 'Node Unselected', detail: event.node.label});
    }

    nodeExpandMessage(event) {
        this.msgs = [];
        this.msgs.push({severity: 'info', summary: 'Node Expanded', detail: event.node.label});
    }

    nodeExpand(event) {
        if(event.node) {
            //in a real application, make a call to a remote url to load children of the current node and add the new nodes as children
            this.nodeService.getLazyFiles().then(nodes => event.node.children = nodes);
        }
    }

    viewFile(file: TreeNode) {
        this.msgs = [];
        this.msgs.push({severity: 'info', summary: 'Node Selected with Right Click', detail: file.label});
    }

    unselectFile() {
        this.selectedFile2 = null;
    }

    expandAll(){
        this.filesTree6.forEach( node => {
            this.expandRecursive(node, true);
        } );
    }

    collapseAll(){
        this.filesTree6.forEach( node => {
            this.expandRecursive(node, false);
        } );
    }

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