Getting Started with Tree Web Component

Smart UI Web Components work with current evergreen browsers and Node 18+ for local tooling; pin package versions to match your project policy.

Smart UI is distributed as the smart-webcomponents NPM package. You can also use the full download from the Download page.

Quick start

  1. Install the package:

    npm install smart-webcomponents

  2. Load the Tree module (ES module script):

    <script type="module" src="node_modules/smart-webcomponents/source/modules/smart.tree.js"></script>

  3. Add the default stylesheet (prefer angular.json / bundler entry in app codebases; for plain HTML use a link):

    <link rel="stylesheet" type="text/css" href="node_modules/smart-webcomponents/source/styles/smart.default.css" />

  4. Add markup in one of two ways - semantic custom element (the component tag is in your HTML) or a host div (you mount programmatically with appendTo):

    Semantic element (id matches the selector in Smart()):

    <smart-tree id="tree"></smart-tree>

    Host container (id matches appendTo on Smart.Tree):

    <div id="treeContainer"></div>

  5. Initialize after the module loads: define a const treeOptions object, then either bind with Smart('#tree', ...) on the semantic tag or use new Smart.Tree({ ...treeOptions, appendTo: '#treeContainer' }) on the host div:

    <script type="module">
    	import 'node_modules/smart-webcomponents/source/modules/smart.tree.js';
    
    	const treeOptions = { selectedIndexes: ["0.1"] };
    
    	// Option A - semantic <smart-tree> with id="tree"
    	Smart('#tree', class {
    		get properties() {
    			return treeOptions;
    		}
    	});
    
    	// Option B - host div id="treeContainer"
    	// const treeInstance = new Smart.Tree({
    	// 	...treeOptions,
    	// 	appendTo: '#treeContainer'
    	// });
    
    	// Option C - constructor(selector, options), then append the returned element yourself
    	// const myTree = new Smart.Tree('#tree', treeOptions);
    	// document.body.appendChild(myTree);
    </script>
    		

    Uncomment Option B when you use the host div; use Option A when you use the semantic element. The Runtime cookbook also documents new Smart.Tree('#tree', treeOptions) with appendChild, and document.createElement('smart-tree') with .props or Object.assign (all are valid patterns; do not combine overlapping patterns for the same instance unless you intend multiple components).

  6. Serve the folder over HTTP (or use your bundler dev server) and open the page.

Runtime cookbook

Alternative creation patterns and imperative APIs. These are all valid ways to create Smart UI components: semantic markup + Smart(); new Smart.Tree({ ...options, appendTo: '#...' }); new Smart.Tree('#tree', treeOptions) plus appendChild on the returned element; and document.createElement('smart-tree') then assigning options via .props or Object.assign on the element.

Constructor with a selector string and options, then append the returned element (for example const myTree = new Smart.Tree('#tree', treeOptions)):

	const treeOptions = { selectedIndexes: ["0.1"] };
	const myTree = new Smart.Tree('#tree', treeOptions);
	document.body.appendChild(myTree);
	

Create with document.createElement('smart-tree'), assign properties (same as any custom element), then append:

	const treeOptions = { selectedIndexes: ["0.1"] };
	const tree = document.createElement('smart-tree');
	Object.assign(tree, treeOptions);
	document.body.appendChild(tree);
	

Host on a div with appendTo (import the module, then instantiate when the document is ready; the container id must match appendTo):

	import "../../source/modules/smart.tree.js";

	document.readyState === 'complete' ? init() : window.addEventListener('load', init);

	function init() {
		const treeOptions = { selectedIndexes: ["0.1"] };
		const tree = new Smart.Tree({
			...treeOptions,
			appendTo: '#treeContainer'
		});
	}
	

Demo

Appearance

The tree structure contains smart-tree-item and smart-tree-items-group elements.

The following attributes are available for these custom elements.

  • label - the label to be displayed in the Tree
  • level - level of nesting
  • selected - selected state of the element
  • value - a custom value that is not displayed, but is passed as an argument to the itemClick event (called when an item is chosen).
  • separator - if present, a visual separator (horizontal line) is added after the item
  • disabled - disables the selection of an item

The following attribute is only available for smart-tree-item.

  • shortcut - a helper text/icon that can represent a keyboard shortcut that activates the item.

The following attribute is only available for smart-tree-items-group.

  • expanded - controls expand/collapse

Animated tree could be achieved when animation class is added .

 <smart-tree class="animation"></smart-tree>

By setting selectionMode property, smart-tree has several types of selection:

  • none
  • oneOrManyExtended
  • zeroOrMany
  • oneOrMany
  • zeroOrOne
  • one
  • checkBox
  • radioButton

In selectionMode: checkBox can be enabled "hasThreeStates". In this case sub-item selection affects the selection of parent items.

 <smart-tree selection-mode="checkBox"></smart-tree>

Demo

To display multi-level hierarchy, Smart.Tree uses connectiong lines, displaying the relations between tree items and groups. They are controlled by showLines property. Smart.Tree also supports guiding lines from each item to the root item. This feature is controlled by showRootLines property.

 <smart-tree show-lines show-root-lines></smart-tree>

Demo

Smart.Tree allows two scrolling modes - 'scrollbar' and 'scrollButtons'.
In the following example is shown the behavior of these two modes, in different oferflow settings.

 <smart-tree filterable scroll-mode="scrollbar"></smart-tree>
 <smart-tree filterable scroll-mode="scrollButtons"></smart-tree>

Demo

toggleElementPosition is used for positioning togle elements on left or right side. Allows two options - 'near' and 'far'.,

 <smart-tree toggle-element-position="far"></smart-tree>

Demo

Data Biding

To initialize a populated Smart.Tree custom element, insert the required inner structure consisting of the auxiliary custom elements smart-menu-item and smart-menu-items-group, e.g.:

<!DOCTYPE html>
<html lang="en">
<head>
 <link rel="stylesheet" href="../../source/styles/smart.default.css" type="text/css" />
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.22/webcomponents-lite.min.js">
</script> <script type="text/javascript" src="../../source/Smart.element.js"></script> <script type="text/javascript" src="../../source/Smart.button.js"></script> <script type="text/javascript" src="../../source/Smart.menu.js"></script> <script type="text/javascript" src="../../source/Smart.scrollbar.js"></script> <script type="text/javascript" src="../../source/Smart.Tree.js"></script> </head> <body> <smart-tree id="tree" class="animation"> <smart-tree-items-group> Cats <smart-tree-item>Tiger</smart-tree-item> <smart-tree-item>Lion</smart-tree-item> <smart-tree-item>Jaguar</smart-tree-item> <smart-tree-item>Leopard</smart-tree-item> <smart-tree-item>Serval</smart-tree-item> <smart-tree-item>Domestic cat</smart-tree-item> </smart-tree-items-group> <smart-tree-items-group> Dogs <smart-tree-item>Gray wolf</smart-tree-item> <smart-tree-item>Ethiopian wolf</smart-tree-item> <smart-tree-item>Arctic fox</smart-tree-item> <smart-tree-item>Dingo</smart-tree-item> <smart-tree-item>Domestic dog</smart-tree-item> </smart-tree-items-group> </smart-tree> </body> </html>

Populating from dataSource.

<!DOCTYPE html>
<html lang="en">
<head>
 <link rel="stylesheet" href="../../source/styles/smart.default.css" type="text/css" />
 <script type="text/javascript" src="../../source/modules/smart.tree.js"></script>
 <script>
 window.onload = function () {
     document.querySelector('smart-tree').dataSource = [{
                label: 'Cats',
                selected: true,
                items: [
                    {
                        label: 'Tiger',
                        selected: true
                    },
                    {
                        label: 'Lion'
                    },
                    {
                        label: 'Jaguar'
                    },
                    {
                        label: 'Leopard'
                    },
                    {
                        label: 'Serval'
                    },
                    {
                        label: 'Domestic cat'
                    }
                ]
            },
                {
                    label: 'Dogs',
                    expanded: true,
                    items: [
                        {
                            label: 'Gray wolf'
                        },
                        {
                            label: 'Ethiopian wolf',
                            selected: true
                        },
                        {
                            label: 'Arctic fox',
                            selected: true
                        },
                        {
                            label: 'Dingo'
                        },
                        {
                            label: 'Domestic dog',
                            selected: true
                        }
                    ]
                }
            ];
     }
 </script>
</head>
<body>
    <smart-tree></smart-tree>
</body>
</html>

Demo

Behavior

Smart.Tree allows three optionsof user interaction used for expanding or collapsing item groups. They are available as settings of toggleMode property:

  • click - single click on group's label toggles the group.
  • dblclick - double click on group's label toggles the group(default setting).
  • arrow - clicking only on group's arrow toggles the group. Clicking group's label doesn't affect the state.
 <smart-tree toggle-mode="arrow"></smart-tree>

Demo

Tree items could be moved in tree's structure and/or between different tree instances. This behavior can be achieved via allowDrag and allowDrop properties.

  • allowDrag - items of a tree with allowDrag set to true can be dragged. When the dragginng starts is fired 'dragStart' event.
  • allowDrop - allows drop in the focussed tree of items that are its children or children of another tree. On drop is fired 'dragEnd' event.

event.preventDefault() of both events prevents drag/drop(depending of event type). It can be used to deny drag or drop functionality of particular Smart.Tree item.

 <smart-tree  class="animation" allow-drag allow-drop></smart-tree>
 <smart-tree  class="animation" allow-drag allow-drop></smart-tree>

Demo

Filtering feature is unlocked by setting filterable to true. This will show filter input. The element filters by particular criteria items in all levels and shows only these who matched the criteria. By setting filterInputPlaceholder to custom text, could be changed the placeholder of this element.
smart-tree allows few filtering options. They can be set by filterMode property:

  • contains
  • containsIgnoreCase
  • doesNotContain
  • doesNotContainIgnoreCase
  • equals
  • equalsIgnoreCase
  • startsWith
  • startsWithIgnoreCase
  • endsWith
  • endsWithIgnoreCase
 <smart-tree filterable filter-input-placeholder="Filter query..." filter-mode="containsIgnoreCase"></smart-tree>

Demo

Methods

The element offers the following methods:

  • addAfter - Adds an item after another item as a sibling.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree'),
                newItem = document.createElement('smart-tree-item');
             newItem.innerHTML = '0';
             tree.addAfter(newItem, 'three');
         }
     </script>
    
  • addBefore - adds new item to the tree.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree'),
                newItem = document.createElement('smart-tree-item');
             newItem.label = 'Y';
             tree.addBefore(newItem, 'zed');
         }
     </script>
    
  • addTo - Adds an item as the last child of a parent item.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree'),
                newItem = document.createElement('smart-tree-item');
             newItem.label = 'D';
             tree.addTo(newItem, 'letters');
         }
     </script>
    
  • clearSelection - clearSelection
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.clearSelection();
         }
     </script>
    
  • collapseAll - Collapses all items.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.collapseAll();
         }
     </script>
    
  • ensureVisible - Makes sure an item is visible by scrolling to it.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.ensureVisible('0.0');
         }
     </script>
    
  • expandAll - Expands all items.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.expandAll();
         }
     </script>
    
  • expandItem - Expands an item.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.expandItem('0.0');
         }
     </script>
    
  • filter - Filters the Tree.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.filter();
         }
     </script>
    
  • getState - Returns Smart.Tree's state
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.getState();
         }
     </script>
    
  • loadState - Loads the Tree's state.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.loadState();
         }
     </script>
    
  • moveDown - Moves an item down relative to its siblings.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.moveDown('0.0');
         }
     </script>
    
  • moveUp - Moves an item up relative to its siblings.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.moveUp('0.0');
         }
     </script>
    
  • removeItem - Removes an item.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.removeItem('0.0');
         }
     </script>
    
  • saveState - Saves the Tree's state.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.saveState();
         }
     </script>
    
  • select - Selects an item.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.select('0.0');
         }
     </script>
    
  • unselect - Unselects an item.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.unselect('0.0');
         }
     </script>
    
  • updateItem - Updates an item.
     <script>
         window.onload = function () {
             let tree = document.querySelector('smart-tree');
             tree.updateItem('0.0', { disabled: false });
         }
     </script>
    

Keyboard Support

Key Action
Tab The Tree receives focus by tabbing into it.
Arrow Up / Arrow Down Navigation between visible items.
Left Arrow On an expanded item, collapses the item. On a collapsed or a "leaf" item moves focus to the item's parent item.
Right Arrow On a collapsed item expands the item. On an expanded item, moves to the first child item, or does nothing on a "leaf" item.
Home Moves to the top enabled item.
End Moves to the last enabled item.
Enter Expands/collapses an item or selects a "leaf" item.
Escape If the menu is minimized, closes the minimized pop-up.
Space Toggles an item's checked state.

Append to the DOM:

const container = document.getElementById('tree-container');
container.appendChild(tree);
	

Remove from the DOM:

tree.remove();
	

Set a property:

tree.disabled = true;
tree.theme = 'dark';
	

Get a property value:

const isDisabled = tree.disabled;
const currentTheme = tree.theme;
	

Invoke a method:

tree.refresh();
tree.focus();
	

Add event listener:

tree.addEventListener('change', (event) => {
    console.log('change triggered:', event.detail.item);
});
	

Remove event listener:

const handleTreeEvent = (event) => {
    console.log('change triggered:', event.detail.item);
};

tree.addEventListener('change', handleTreeEvent);
tree.removeEventListener('change', handleTreeEvent);
	

Common Use Cases

  • Load hierarchical data

    Populate tree with nested items

    tree.dataSource = [{
      label: 'Parent',
      items: [
        { label: 'Child 1' },
        { label: 'Child 2' }
      ]
    }];
  • Expand/collapse nodes

    Programmatically control node state

    tree.expandItem('0'); // Expand first item
    tree.collapseItem('0'); // Collapse it
  • Handle selection

    Respond to tree item selection

    tree.addEventListener('change', (e) => {
      console.log('Selected:', e.detail.value);
    });

Troubleshooting

How do I load tree data lazily?
Set items to a function that returns a Promise, or use the expanding event to load child nodes on demand.
How do I enable drag and drop?
Set allowDrag = true and allowDrop = true to enable drag-and-drop reordering.

Accessibility

The Tree component follows WAI-ARIA best practices:

  • Keyboard navigation - Tab, Arrow keys, Enter, and Escape are supported
  • ARIA roles - Appropriate roles and labels are applied automatically
  • Focus management - Visible focus indicators for keyboard users
  • Screen readers - State changes are announced to assistive technology
  • High contrast - Supports Windows High Contrast Mode and forced colors

For custom labeling, set aria-label or aria-labelledby attributes on the component.

Live demos

Supported stacks: Smart UI targets Angular 17+, React 18+, Vue 3+, Node 18 LTS, and evergreen browsers; pin exact package versions to your org policy.