The TreeView control displays a hierarchical list of TreeNode objects which may contain text, checkboxes, images, or arbitrary HTML content.
A TreeView is typically used to display the headings in a document, the entries in an index, the files and directories on a disk, or any other kind of information that might usefully be displayed as a hierarchy.
After creating a TreeView, you will typically set the following properties:
The TreeView control supports the following keyboard commands:
Key Combination | Action |
---|---|
Up/Down | Select the previous/next visible node |
Left | Collapse the selected node if it has child nodes, select the parent node otherwise |
Right | Expand the selected node if it has child nodes |
Home/End | Select the first/last visible nodes |
Space | Toggle the checkbox in the current node (see the showCheckboxes property) |
Other characters | Search for nodes that contain the text typed (multi-character auto-search) |
The example below builds a simple tree and allows you to see the effect of the TreeView's main properties:
{@sample Nav/TreeView/Behavior/purejs Example}
constructor(element: any, options: any): TreeView
Initializes a new instance of the TreeView class.
The DOM element that hosts the control, or a CSS selector for the host element (e.g. '#theCtrl').
The JavaScript object containing initialization data for the control.
Gets or sets a value that determines whether users can drag and drop nodes within the TreeView.
The default value for this property is **false**.
Gets or sets a value that determines if sibling nodes should be collapsed when a node is expanded.
The default value for this property is **true**, because in most cases collapsing nodes that are not in use helps keep the UI clean.
Gets an array containing the items that are currently checked.
The array returned includes only items that have no children. This is because checkboxes in parent items are used to check or uncheck the child items.
See also the showCheckboxes property and the checkedItemsChanged event.
For example:
import { TreeView } from '@mescius/wijmo.nav'; var treeViewChk = new TreeView('#gsTreeViewChk', { displayMemberPath: 'header', childItemsPath: 'items', showCheckboxes: true, itemsSource: items, checkedItemsChanged: function (s, e) { var items = s.checkedItems, msg = ''; if (items.length) { msg = '<p><b>Selected Items:</b></p><ol>\r\n'; for (var i = 0; i < items.length; i++) { msg += '<li>' + items[i].header + '</li>\r\n'; } msg += '</ol>'; } document.getElementById('gsTreeViewChkStatus').innerHTML = msg; } });
Gets or sets the name of the property (or properties) to bind to the node's checked state.
See also the showCheckboxes property and the checkedItemsChanged event.
Gets or sets a value that determines whether to toggle checkboxes when the user clicks the node header.
The default value for this property is **false**, which causes checkboxes to be toggled only when the user clicks the checkbox itself (not the node header).
See also the showCheckboxes property and the checkedItemsChanged event.
Gets or sets the name of the property (or properties) that contains the child items for each node.
The default value for this property is the string **"items"**.
In most cases, the property that contains the child items is the same for all data items on the tree. In these cases, set the childItemsPath to that name.
In some cases, however, items at different levels use different properties to store their child items. For example, you could have a tree with categories, products, and orders. In that case, you would set the childItemsPath to an array such as this:
// categories have products, products have orders: tree.childItemsPath = [ 'Products', 'Orders' ];
Gets or sets a value that determines whether to collapse expanded nodes when the user clicks the node header.
The default value for this property is **false**.
When this property is set to **false**, users have to click the expand/collapse icons to collapse the node. Clicking the node header will select the node if it is not selected, and will start editing the node if it is selected (and if the isReadOnly property is set to false).
See also the expandOnClick property.
Gets or sets a value that determines whether nodes should be collapsed when they are disabled.
The default value for this property is **true**.
Gets or sets the template used to instantiate TreeView controls.
Gets or sets the name of the property (or properties) to use as the visual representation of the nodes.
The default value for this property is the string **"header"**.
In most cases, the property that contains the node text is the same for all data items on the tree. In these cases, set the displayMemberPath to that name.
In some cases, however, items at different levels use different properties to represent them. For example, you could have a tree with categories, products, and orders. In that case, you might set the displayMemberPath to an array such as this:
// categories, products, and orders have different headers: tree.displayMemberPath = [ 'CategoryName', 'ProductName', 'OrderID' ];
Gets or sets a value that determines whether to expand collapsed nodes when the user clicks the node header.
The default value for this property is **true**.
When this property is set to **false**, users have to click the expand/collapse icons to collapse the node. Clicking the node header will select the node if it is not selected, and will start editing the node if it is selected (and if the isReadOnly property is set to false).
See also the collapseOnClick property.
Gets or sets a value that determines whether to automatically expand the first node when the tree is loaded.
The default value for this property is **true**. If you set it to false, all nodes will be initially collapsed.
Gets the DOM element that is hosting the control.
Gets or sets the name of the property (or properties) to use as a source of images for the nodes.
The default value for this property is an empty string, which means no images are added to the nodes.
Gets or sets a value that indicates whether to use animations when expanding or collapsing nodes.
The default value for this property is **true**.
Gets or sets a value indicating whether items are bound to plain text or HTML.
The default value for this property is **false**.
Gets or sets a value that determines whether the control is disabled.
Disabled controls cannot get mouse or keyboard events.
Gets or sets a value that determines whether users can edit the text in the nodes.
When the isReadOnly property is set to false, users may edit the content of the tree nodes by typing directly into the nodes. The F2 key can also be used to enter edit mode with the whole node content selected.
You may customize the editing behavior using the following methods and events:
**Methods**: startEditing, finishEditing.
**Events**: nodeEditStarting, nodeEditStarted, nodeEditEnding, nodeEditEnded.
The default value for this property is **true**.
Gets a value that indicates whether the control is currently handling a touch event.
Gets a value that indicates whether the control is currently being updated.
Gets or sets the array that contains the TreeView items.
TreeView #see:itemsSource arrays usually have a hierarchical structure with items that contain child items. There is no fixed limit to the depth of the items.
For example, the array below would generate a tree with three top-level nodes, each with two child nodes:
import { TreeView } from '@mescius/wijmo.nav'; var tree = new TreeView('#treeView', { displayMemberPath: 'header', childItemsPath: 'items', itemsSource: [ { header: '1 first', items: [ { header: '1.1 first child' }, { header: '1.2 second child' }, ] }, { header: '2 second', items: [ { header: '3.1 first child' }, { header: '3.2 second child' }, ] }, { header: '3 third', items: [ { header: '3.1 first child' }, { header: '3.2 second child' }, ] } ] });
Gets or sets a function that loads child nodes on demand.
The lazyLoadFunction takes two parameters: the node being expanded and a callback to be invoked when the data becomes available.
The callback function tells the TreeView that the node loading process has been completed. It should always be called, even if there are errors when loading the data.
For example:
import { TreeView } from '@mescius/wijmo.nav'; var treeViewLazyLoad = new TreeView('#treeViewLazyLoad', { displayMemberPath: 'header', childItemsPath: 'items', itemsSource: [ // start with three lazy-loaded nodes { header: 'Lazy Node 1', items: []}, { header: 'Lazy Node 2', items: [] }, { header: 'Lazy Node 3', items: [] } ], lazyLoadFunction: function (node, callback) { setTimeout(function () { // simulate http delay var result = [ // simulate result { header: 'Another lazy node...', items: [] }, { header: 'A non-lazy node without children' }, { header: 'A non-lazy node with child nodes', items: [ { header: 'hello' }, { header: 'world' } ]} ]; callback(result); // return result to control }, 2500); // simulated 2.5 sec http delay } });
Trees with lazy-loaded nodes have some restrictions: their nodes may not have checkboxes (see the showCheckboxes property) and the collapseToLevel method will not expand collapsed nodes that have not been loaded yet.
Gets a value indicating whether the control is hosted in an element with right-to-left layout.
Gets or sets the data item that is currently selected.
Gets an array containing the text of all nodes from the root to the currently selected node.
Gets or sets a value that determines whether the TreeView should add checkboxes to nodes and manage their state.
This property can be used only on trees without lazy-loaded nodes (see the lazyLoadFunction property).
See also the checkedItems property and checkedItemsChanged event.
The default value for this property is **false**.
Gets or sets a value of the **tabindex** attribute associated with the control.
**tabindex** attribute value can be defined statically for a Wijmo control by specifying it on the control's host HTML element. But this value can't be changed later during application lifecycle, because Wijmo controls have complex structure, and the control may need to propagate this attribute value to its internal element to work properly.
Because of this, to read or change control's **tabindex** dynamically, you should do it using this property.
addChildNode(index: number, dataItem: any): TreeNode
Adds a child node at a specific position.
Index of the new child node.
Data item used to create the new node.
addEventListener(target: EventTarget, type: string, fn: any, capture?: boolean, passive?: boolean): void
Adds an event listener to an element owned by this Control.
The control keeps a list of attached listeners and their handlers, making it easier to remove them when the control is disposed (see the dispose and removeEventListener methods).
Failing to remove event listeners may cause memory leaks.
The passive parameter is set to false by default, which means the event handler may call event.preventDefault(). If you are adding passive handlers to touch or wheel events, setting this parameter to true will improve application performance.
For details on passive event listeners, please see Improving scrolling performance with passive listeners.
Target element for the event.
String that specifies the event.
Function to execute when the event occurs.
Whether the listener should be handled by the control before it is handled by the target element.
Indicates that the handler will never call preventDefault().
applyTemplate(classNames: string, template: string, parts: Object, namePart?: string): HTMLElement
Applies the template to a new instance of a control, and returns the root element.
This method should be called by constructors of templated controls. Therefore, this method is not available. It is responsible for binding the template parts to the corresponding control members.
For example, the code below applies a template to an instance of an InputNumber control. The template must contain elements with the 'wj-part' attribute set to 'input', 'btn-inc', and 'btn-dec'. The control members '_tbx', '_btnUp', and '_btnDn' will be assigned references to these elements.
this.applyTemplate('wj-control wj-inputnumber', templateString, { _tbx: 'input', _btnUp: 'btn-inc', _btnDn: 'btn-dec' }, 'input');```
Names of classes to add to the control's host element.
An HTML string that defines the control template.
A dictionary of part variables and their names.
Name of the part to be named after the host element. This determines how the control submits data when used in forms.
beginUpdate(): void
Suspends notifications until the next call to endUpdate.
checkAllItems(check: boolean): void
Checks or unchecks all checkboxes on the tree.
Whether to check or uncheck all checkboxes.
collapseToLevel(level: number): void
Collapses all the tree items to a given level.
This method will typically expand or collapse multiple nodes at once. But it will not perform lazy-loading on any nodes, so collapsed nodes that must be lazy-loaded will not be expanded.
Maximum node level to show.
deferUpdate(fn: Function): void
Executes a function within a beginUpdate/endUpdate block.
The control will not be updated until the function has been executed. This method ensures endUpdate is called even if the function throws an exception.
Function to be executed.
dispose(): void
Disposes of the control by removing its association with the host element.
The dispose method automatically removes any event listeners added with the addEventListener method.
Calling the dispose method is important in applications that create and remove controls dynamically. Failing to dispose of the controls may cause memory leaks.
disposeAll(e?: HTMLElement): void
Disposes of all Wijmo controls contained in an HTML element.
Container element.
endUpdate(): void
Resumes notifications suspended by calls to beginUpdate.
finishEditing(cancel?: boolean): boolean
Commits any pending edits and exits edit mode.
Whether pending edits should be canceled or committed.
getControl(element: any): Control
Gets the control that is hosted in a given DOM element.
The DOM element that hosts the control, or a CSS selector for the host element (e.g. '#theCtrl').
getFirstNode(visible?: boolean, enabled?: boolean): TreeNode
Whether to return only visible nodes (whose ancestors are not collapsed).
Whether to return only enabled nodes (whose ancestors are not disabled).
getLastNode(visible?: boolean, enabled?: boolean): TreeNode
Whether to return only visible nodes (whose ancestors are not collapsed).
Whether to return only enabled nodes (whose ancestors are not disabled).
getNode(item: any): TreeNode
Gets the TreeNode object representing a given data item.
The data item to look for.
getTemplate(): string
Gets the HTML template used to create instances of the control.
This method traverses up the class hierarchy to find the nearest ancestor that specifies a control template. For example, if you specify a prototype for the ComboBox control, which does not specify a template, it will override the template defined by the DropDown base class (the nearest ancestor that does specify a template).
initialize(options: any): void
Initializes the control by copying the properties from a given object.
This method allows you to initialize controls using plain data objects instead of setting the value of each property in code.
For example:
grid.initialize({
itemsSource: myList,
autoGenerateColumns: false,
columns: [
{ binding: 'id', header: 'Code', width: 130 },
{ binding: 'name', header: 'Name', width: 60 }
]
});
// is equivalent to
grid.itemsSource = myList;
grid.autoGenerateColumns = false;
// etc.
The initialization data is type-checked as it is applied. If the initialization object contains unknown property names or invalid data types, this method will throw.
Object that contains the initialization data.
invalidate(fullUpdate?: boolean): void
Invalidates the control causing an asynchronous refresh.
Whether to update the control layout as well as the content.
invalidateAll(e?: HTMLElement): void
Invalidates all Wijmo controls contained in an HTML element.
Use this method when your application has dynamic panels that change the control's visibility or dimensions. For example, splitters, accordions, and tab controls usually change the visibility of its content elements. In this case, failing to notify the controls contained in the element may cause them to stop working properly.
If this happens, you must handle the appropriate event in the dynamic container and call the invalidateAll method so the contained Wijmo controls will update their layout information properly.
Container element. If set to null, all Wijmo controls on the page will be invalidated.
loadTree(preserveOutlineState?: boolean): void
Loads the tree using data from the current itemsSource.
Whether to preserve the outline state when loading the tree data. Defaults to false.
onCheckedItemsChanged(e?: EventArgs): void
Raises the checkedItemsChanged event.
onDragEnd(e?: EventArgs): void
Raises the dragEnd event.
onDragOver(e: TreeNodeDragDropEventArgs): boolean
Raises the dragOver event.
TreeNodeDragDropEventArgs that contains the event data.
onDragStart(e: TreeNodeEventArgs): boolean
Raises the dragStart event.
TreeNodeEventArgs that contains the event data.
onDrop(e: TreeNodeDragDropEventArgs): boolean
Raises the drop event.
TreeNodeDragDropEventArgs that contains the event data.
onFormatItem(e: FormatNodeEventArgs): void
Raises the formatItem event.
FormatNodeEventArgs that contains the event data.
onGotFocus(e?: EventArgs): void
Raises the gotFocus event.
onInvalidInput(e: CancelEventArgs): void
Raises the invalidInput event.
If the event handler cancels the event, the control will keep the invalid input and the focus.
onIsCheckedChanged(e: TreeNodeEventArgs): void
Raises the isCheckedChanged event.
TreeNodeEventArgs that contains the event data.
onIsCheckedChanging(e: TreeNodeEventArgs): boolean
Raises the isCheckedChanging event.
TreeNodeEventArgs that contains the event data.
onIsCollapsedChanged(e: TreeNodeEventArgs): void
Raises the isCollapsedChanged event.
TreeNodeEventArgs that contains the event data.
onIsCollapsedChanging(e: TreeNodeEventArgs): boolean
Raises the isCollapsedChanging event.
TreeNodeEventArgs that contains the event data.
onItemClicked(e?: EventArgs): void
Raises the itemClicked event.
onItemsSourceChanged(e?: EventArgs): void
Raises the itemsSourceChanged event.
onLoadedItems(e?: EventArgs): void
Raises the loadedItems event.
onLoadingItems(e?: CancelEventArgs): boolean
Raises the loadingItems event.
onLostFocus(e?: EventArgs): void
Raises the lostFocus event.
onNodeEditEnded(e: TreeNodeEventArgs): void
Raises the nodeEditEnded event.
TreeNodeEventArgs that contains the event data.
onNodeEditEnding(e: TreeNodeEventArgs): boolean
Raises the nodeEditEnding event.
TreeNodeEventArgs that contains the event data.
onNodeEditStarted(e: TreeNodeEventArgs): void
Raises the nodeEditStarted event.
TreeNodeEventArgs that contains the event data.
onNodeEditStarting(e: TreeNodeEventArgs): boolean
Raises the nodeEditStarting event.
TreeNodeEventArgs that contains the event data.
onRefreshed(e?: EventArgs): void
Raises the refreshed event.
onRefreshing(e?: EventArgs): void
Raises the refreshing event.
onSelectedItemChanged(e?: EventArgs): void
Raises the selectedItemChanged event.
refresh(fullUpdate?: boolean): void
Overridden to re-populate the tree.
Indicates whether to update the control layout as well as the content.
refreshAll(e?: HTMLElement): void
Refreshes all Wijmo controls contained in an HTML element.
This method is similar to invalidateAll, except the controls are updated immediately rather than after an interval.
Container element. If set to null, all Wijmo controls on the page will be invalidated.
removeEventListener(target?: EventTarget, type?: string, fn?: any, capture?: boolean): number
Removes one or more event listeners attached to elements owned by this Control.
Target element for the event. If null, removes listeners attached to all targets.
String that specifies the event. If null, removes listeners attached to all events.
Handler to remove. If null, removes all handlers.
Whether the listener is capturing. If null, removes capturing and non-capturing listeners.
startEditing(node?: TreeNode): boolean
Starts editing a given TreeNode.
Occurs when the value of the checkedItems property changes.
See also the showCheckboxes and checkOnClick properties.
Occurs when the user finishes a drag/drop operation, either by dropping a node into a new location or by canceling the operation with the mouse or keyboard.
Occurs while the user drags a node over other nodes on the TreeView.
This event only occurs if the allowDragging property is set to true.
You may prevent drop operations over certain nodes and/or positions by setting the event's **cancel** parameter to true.
Occurs when the user starts dragging a node.
This event only occurs if the allowDragging property is set to true.
You may prevent nodes from being dragged by setting the event's **cancel** parameter to true.
Occurs when an element representing a node has been created.
This event can be used to format nodes for display.
The example below uses the **formatItem** event to add a "new" badge to the right of new items on the tree.
import { TreeView } from '@mescius/wijmo.nav';
var treeViewFmtItem = new TreeView('#treeViewFmtItem', {
displayMemberPath: 'header',
childItemsPath: 'items',
itemsSource: items,
formatItem: function (s, e) {
if (e.dataItem.newItem) {
let img = wijmo.createElement('<img style="margin-left:6px" src="resources/new.png"/>');
e.element.appendChild(img);
}
}
});
Occurs when invalid input is detected.
Invalid input may occur when the user types or pastes a value that cannot be converted to the proper type, or a value that is outside the valid range.
If the event handler cancels the event, the control will retain the invalid content and the focus, so users can correct the error.
If the event is not canceled, the control will ignore the invalid input and will retain the original content.
Occurs after the value of the isChecked property changes.
Occurs before the value of the isChecked property changes.
Occurs after the value of the isCollapsed property changes.
Occurs before the value of the isCollapsed property changes.
Occurs when the user clicks an item or presses the Enter key and an item is selected.
This event is typically used in navigation trees. Use the selectedItem property to get the item that was clicked.
Occurs after the control has refreshed its contents.
Occurs when the control is about to refresh its contents.