DEV Community

loading...
Cover image for Angular Tree

Angular Tree

PrimeTek
PrimeTek is a world renowned vendor of popular UI Component suites including PrimeFaces, PrimeNG, PrimeReact and PrimeVue. For any inquires please use contact@primetek.com.tr to contact us.
・7 min read

Angular Tree is used to display hierarchical data.

Setup

Refer to PrimeNG setup documentation for download and installation steps for your environment.

CDK

VirtualScrolling depends on @angular/cdk's ScrollingModule so begin with installing CDK if not already installed.

npm install @angular/cdk --save
Enter fullscreen mode Exit fullscreen mode

Import

import {TreeModule} from 'primeng/tree';
import {TreeNode} from 'primeng/api';
Enter fullscreen mode Exit fullscreen mode

Getting Started

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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": "pi pi-folder-open",
            "collapsedIcon": "pi pi-folder",
            "children": [{
                    "label": "Work",
                    "data": "Work Folder",
                    "expandedIcon": "pi pi-folder-open",
                    "collapsedIcon": "pi pi-folder",
                    "children": [{"label": "Expenses.doc", "icon": "pi pi-file", "data": "Expenses Document"}, {"label": "Resume.doc", "icon": "pi pi-file", "data": "Resume Document"}]
                },
                {
                    "label": "Home",
                    "data": "Home Folder",
                    "expandedIcon": "pi pi-folder-open",
                    "collapsedIcon": "pi pi-folder",
                    "children": [{"label": "Invoices.txt", "icon": "pi pi-file", "data": "Invoices for this month"}]
                }]
        },
        {
            "label": "Pictures",
            "data": "Pictures Folder",
            "expandedIcon": "pi pi-folder-open",
            "collapsedIcon": "pi pi-folder",
            "children": [
                {"label": "barcelona.jpg", "icon": "pi pi-image", "data": "Barcelona Photo"},
                {"label": "logo.jpg", "icon": "pi pi-file", "data": "PrimeFaces Logo"},
                {"label": "primeui.png", "icon": "pi pi-image", "data": "PrimeUI Logo"}]
        },
        {
            "label": "Movies",
            "data": "Movies Folder",
            "expandedIcon": "pi pi-folder-open",
            "collapsedIcon": "pi pi-folder",
            "children": [{
                    "label": "Al Pacino",
                    "data": "Pacino Movies",
                    "children": [{"label": "Scarface", "icon": "pi pi-video", "data": "Scarface Movie"}, {"label": "Serpico", "icon": "pi pi-file-video", "data": "Serpico Movie"}]
                },
                {
                    "label": "Robert De Niro",
                    "data": "De Niro Movies",
                    "children": [{"label": "Goodfellas", "icon": "pi pi-video", "data": "Goodfellas Movie"}, {"label": "Untouchables", "icon": "pi pi-video", "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);
    }

}
Enter fullscreen mode Exit fullscreen mode
<p-tree [value]="files"></p-tree>
Enter fullscreen mode Exit fullscreen mode

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);
    }

}
Enter fullscreen mode Exit fullscreen mode
<p-tree [value]="files" selectionMode="single" [(selection)]="selectedFile"></p-tree>
Enter fullscreen mode Exit fullscreen mode

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);
        }

    }
Enter fullscreen mode Exit fullscreen mode
<p-tree [value]="files" selectionMode="single" [(selection)]="selectedFiles"></p-tree>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

<p-tree [value]="files" selectionMode="single" [(selection)]="selectedFiles" (onNodeSelect)="nodeSelect($event)" (onNodeUnselect)="nodeUnselect($event)"></p-tree>
Enter fullscreen mode Exit fullscreen mode
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
    }

}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Filtering

Filtering is enabled by setting the filter property to true, by default label property of a node is used to compare against the value in the text field, in order to customize which field(s) should be used during search define filterBy property.

In addition filterMode specifies the filtering strategy. In lenient mode when the query matches a node, children of the node are not searched further as all descendants of the node are included. On the other hand, in strict mode when the query matches a node, filtering continues on all descendants.

<p-tree [value]="filesTree11" [filter]="true"></p-tree>
Enter fullscreen mode Exit fullscreen mode
<p-tree [value]="filesTree12" [filter]="true" filterMode="strict"></p-tree>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode
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);
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

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": "pi pi-folder",
            "collapsedIcon": "pi pi-folder",
            "leaf": false
        },
        {
            "label": "Lazy Node 1",
            "data": "Node 1",
            "expandedIcon": "pi pi-folder-open",
            "collapsedIcon": "pi pi-folder",
            "leaf": false
        },
        {
            "label": "Lazy Node 1",
            "data": "Node 2",
            "expandedIcon": "pi pi-folder-open",
            "collapsedIcon": "pi pi-folder",
            "leaf": false
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Scrolling

Scrolling is used to preserve space as content of the tree is dynamic and enabled by scrollHeight property.

<p-tree [value]="files" scrollHeight="200px"></p-tree>
Enter fullscreen mode Exit fullscreen mode

Flex Scroll

In cases where viewport should adjust itself according to the table parent's height instead of a fixed viewport height, set scrollHeight option as flex. In example below, table is inside a Dialog where viewport size dynamically responds to the dialog size changes such as resizing or maximizing.

<button type="button" (click)="showDialog()" pButton icon="pi pi-external-link" label="View"></button>
<p-dialog header="Flexible ScrollHeight" [(visible)]="dialogVisible" [style]="{width: '50vw'}" [baseZIndex]="10000" [maximizable]="true" [modal]="true" 
    [resizable]="true" [contentStyle]="{height: '300px'}" styleClass="p-fluid">
    <p-tree [value]="files2" scrollHeight="flex"></p-tree>   
</p-dialog>
Enter fullscreen mode Exit fullscreen mode

Virtual Scrolling

VirtualScroller is a performant approach to handle huge data efficiently. Setting virtualScroll property as true and providing a virtualNodeHeight in pixels would be enough to enable this functionality.

<p-tree [value]="files" [virtualScroll]="true" [virtualNodeHeight]="33" scrollHeight="200px"></p-tree>
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode
<p-tree [value]="files" draggableNodes="true" droppableNodes="true"></p-tree>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

In case, a drop should be accepted based on a condition, enable validateDrop property, define an event handler for onNodeDrop where the passed event and call the accept callback of the event to accept a drop. Simply emitting the call of accept() will reject the drop.

<p-tree [value]="files" draggableNodes="true" droppableNodes="true" [validateDrop]="true" (onNodeDrop)="onDrop($event)"></p-tree>
Enter fullscreen mode Exit fullscreen mode
onDrop(event) {
    if (condition) {
        event.accept();
    }
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Horizontal Orientation

Horizontal mode is the alternative option for orientation.

<p-tree [value]="files" layout="horizontal"></p-tree>
Enter fullscreen mode Exit fullscreen mode

Theming

Tree supports various themes featuring Material, Bootstrap, Fluent as well as your own custom themes via the Designer tool.

Resources

Visit the PrimeNG Tree showcase for demos and documentation.

Discussion (0)

Forem Open with the Forem app