Initially
If a node is supposed to be expanded initially, set its expanded field to true. If another field specifies whether a node is expanded or collapsed, assign its name to the expandedExpr property as shown in the following code.
- var hierarchicalData = [{
- name: 'Fruits',
- isExpanded: true,
- items: [
- { name: 'Apples' },
- { name: 'Oranges' }
- ]
- }, {
- name: 'Vegetables',
- isExpanded: true,
- items: [
- { name: 'Cucumbers' },
- { name: 'Tomatoes' }
- ]
- }];
- $(function() {
- $("#treeViewContainer").dxTreeView({
- dataSource: hierarchicalData,
- keyExpr: 'name',
- displayExpr: 'name',
- expandedExpr: 'isExpanded'
- });
- });
Using the API
The TreeView provides the following API to expand and collapse nodes:
All nodes
You can use the expandAll() and collapseAll() methods to expand and collapse nodes at once. Note that the expandAll() method expands only the loaded nodes if data is loaded on demand.JavaScript- $("#treeViewContainer").dxTreeView("expandAll");
- // $("#treeViewContainer").dxTreeView("collapseAll");
Individual nodes
Call the expandItem(key) or collapseItem(key) method and pass a node key as an argument:JavaScript- $("#treeViewContainer").dxTreeView("expandItem", nodeKey);
- // $("#treeViewContainer").dxTreeView("collapseItem", nodeKey);
Events
To execute certain commands when a node is expanded or collapsed, handle the itemExpanded or itemCollapsed event. Assign event handling functions to the onItemExpanded or onItemCollapsed property when you configure the UI component if these functions are going to remain unchanged.
- $(function() {
- $("#treeViewContainer").dxTreeView({
- onItemExpanded: function (e) {
- // Handler of the "itemExpanded" event
- },
- onItemCollapsed: function (e) {
- // Handler of the "itemCollapsed" event
- }
- });
- });
If you are going to change event handlers at runtime, or if you need to attach several handlers to a single event, subscribe to the events using the on(eventName, eventHandler) method.
- var itemCollapsedEventHandler1 = function (e) {
- // First handler of the "itemCollapsed" event
- };
- var itemCollapsedEventHandler2 = function (e) {
- // Second handler of the "itemCollapsed" event
- };
- $("#treeViewContainer").dxTreeView("instance")
- .on("itemCollapsed", itemCollapsedEventHandler1)
- .on("itemCollapsed", itemCollapsedEventHandler2);
See Also
If you have technical questions, please create a support ticket in the DevExpress Support Center.