Your search did not match any results.
Tree View

Drag & Drop for Plain Data Structure

This sample app demonstrates node drag and drop operations within DevExtreme TreeView when using simple data structures. You can reorder nodes within a single tree view or drag and drop nodes between two separate tree views.

Use Sortable to implement the necessary drag and drop functionality within your web app. The following steps outline configuration requirements for our JavaScript TreeView:

  1. Allow users to reorder nodes
    Wrap the TreeView in a Sortable and enable the Sortable's allowReordering option.

  2. Allow users to change node hierarchy
    Enable the allowDropInsideItem option so that users can drop one node onto another. This adds it as the target node's child. If this option is disabled, users can only drop nodes between other nodes.

  3. Allow users to drag only tree view nodes
    To specify tree view nodes as drag targets, set the filter option to a class selector. Since all tree view nodes use the dx-treeview-node class, you can use this class selector as needed.

  4. Prevent a node from being moved into its child node
    When a user moves a parent node into its own child node, it breaks the hierarchy. To prevent this outcome, implement the onDragChange function and traverse up the node tree. If the target is a child of the dragged node, cancel the ability to drop the node.

  5. Reorder nodes in code
    Implement the onDragEnd function. In this function, you must gather information about nodes being moved. With this information, you can reorder the nodes in the data source (see the moveNode function), and reassign the data source to the TreeView's items option.

  6. Specify tree view identifiers (for drag and drop between multiple tree views only)
    Identifiers help distinguish between multiple tree views. Save them in the Sortable's data option. The tree views below include the following identifiers: "driveC" and "driveD".

  7. Combine tree views into one drag and drop group (for drag and drop between multiple tree views only)
    Set the Sortable's group option to the same value for all tree views. This allows users to move nodes between the tree views.

Copy to CodeSandBox
Apply
Reset
<div class="form"> <div class="drive-panel"> <div class="drive-header dx-treeview-item"><i class="dx-icon dx-icon-activefolder"></i><span>Drive C:</span></div> <dx-sortable filter=".dx-treeview-item" group="shared" data="driveC" [allowDropInsideItem]="true" [allowReordering]="true" (onDragChange)="onDragChange($event)" (onDragEnd)="onDragEnd($event)"> <dx-tree-view #treeviewDriveC id="treeviewDriveC" dataStructure="plain" [expandNodesRecursive]="false" [items]="itemsDriveC" [width]="250" [height]="380"> <div *dxTemplate="let item of 'item'"> <div><i class="dx-icon dx-icon-{{ item.isDirectory ? 'activefolder' : 'file' }}"></i><span>{{ item.name }}</span></div> </div> </dx-tree-view> </dx-sortable> </div> <div class="drive-panel"> <div class="drive-header dx-treeview-item"><i class="dx-icon dx-icon-activefolder"></i><span>Drive D:</span></div> <dx-sortable filter=".dx-treeview-item" group="shared" data="driveD" [allowDropInsideItem]="true" [allowReordering]="true" (onDragChange)="onDragChange($event)" (onDragEnd)="onDragEnd($event)"> <dx-tree-view #treeviewDriveD id="treeviewDriveD" dataStructure="plain" [expandNodesRecursive]="false" [items]="itemsDriveD" [width]="250" [height]="380"> <div *dxTemplate="let item of 'item'"> <div><i class="dx-icon dx-icon-{{ item.isDirectory ? 'activefolder' : 'file' }}"></i><span>{{ item.name }}</span></div> </div> </dx-tree-view> </dx-sortable> </div> </div>
import { NgModule, Component, enableProdMode, ViewChild } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { DxTreeViewModule, DxTreeViewComponent, DxSortableModule } from 'devextreme-angular'; import { Service, FileSystemItem } from './app.service'; if(!/localhost/.test(document.location.host)) { enableProdMode(); } @Component({ selector: 'demo-app', templateUrl: 'app/app.component.html', styleUrls: ['app/app.component.css'], providers: [Service] }) export class AppComponent { @ViewChild('treeviewDriveC') treeviewDriveC: DxTreeViewComponent; @ViewChild('treeviewDriveD') treeviewDriveD: DxTreeViewComponent; itemsDriveC: FileSystemItem[]; itemsDriveD: FileSystemItem[]; constructor(service: Service) { this.itemsDriveC = service.getItemsDriveC(); this.itemsDriveD = service.getItemsDriveD(); } onDragChange(e) { if(e.fromComponent === e.toComponent) { const fromNode = this.findNode(this.getTreeView(e.fromData), e.fromIndex); const toNode = this.findNode(this.getTreeView(e.toData), this.calculateToIndex(e)); if (toNode !== null && this.isChildNode(fromNode, toNode)) { e.cancel = true; } } } onDragEnd(e) { if(e.fromComponent === e.toComponent && e.fromIndex === e.toIndex) { return; } const fromTreeView = this.getTreeView(e.fromData); const toTreeView = this.getTreeView(e.toData); const fromNode = this.findNode(fromTreeView, e.fromIndex); const toNode = this.findNode(toTreeView, this.calculateToIndex(e)); if(e.dropInsideItem && toNode !== null && !toNode.itemData.isDirectory) { return; } const fromTopVisibleNode = this.getTopVisibleNode(e.fromComponent); const toTopVisibleNode = this.getTopVisibleNode(e.toComponent); const fromItems = fromTreeView.option('items'); const toItems = toTreeView.option('items'); this.moveNode(fromNode, toNode, fromItems, toItems, e.dropInsideItem); fromTreeView.option('items', fromItems); toTreeView.option('items', toItems); fromTreeView.scrollToItem(fromTopVisibleNode); toTreeView.scrollToItem(toTopVisibleNode); } getTreeView(driveName) { return driveName === 'driveC' ? this.treeviewDriveC.instance : this.treeviewDriveD.instance; } calculateToIndex(e) { if(e.fromComponent != e.toComponent || e.dropInsideItem) { return e.toIndex; } return e.fromIndex >= e.toIndex ? e.toIndex : e.toIndex + 1; } findNode(treeView, index) { const visibleItems = []; this.buildVisibleNodesArray(treeView.getNodes(), visibleItems); if(visibleItems.length <= index) { return null; } return visibleItems[index]; } buildVisibleNodesArray(nodes, arrayContainer) { for(var i = 0; i < nodes.length; i++) { arrayContainer.push(nodes[i]); if(nodes[i].expanded !== false && nodes[i].children){ this.buildVisibleNodesArray(nodes[i].children, arrayContainer); } } } moveNode(fromNode, toNode, fromItems, toItems, isDropInsideItem) { const fromIndex = fromItems.findIndex(item => item.id == fromNode.itemData.id); fromItems.splice(fromIndex, 1); const toIndex = toNode === null || isDropInsideItem ? toItems.length : toItems.findIndex(item => item.id == toNode.itemData.id); toItems.splice(toIndex, 0, fromNode.itemData); this.moveChildren(fromNode, fromItems, toItems); if(isDropInsideItem) { fromNode.itemData.parentId = toNode.itemData.id; } else { fromNode.itemData.parentId = toNode != null ? toNode.itemData.parentId : undefined; } } moveChildren(node, fromDataSource, toDataSource) { if(!node.itemData.isDirectory) { return; } node.children.forEach(child => { if(child.itemData.isDirectory) { this.moveChildren(child, fromDataSource, toDataSource); } const fromIndex = fromDataSource.findIndex(item => item.id == child.itemData.id); fromDataSource.splice(fromIndex, 1); toDataSource.splice(toDataSource.length, 0, child.itemData); }); } isChildNode(parentNode, childNode) { let parent = childNode.parent; while(parent !== null) { if(parent.itemData.id === parentNode.itemData.id) { return true; } parent = parent.parent; } return false; } getTopVisibleNode(component) { const treeViewElement = component.element(); const treeViewTopPosition = treeViewElement.getBoundingClientRect().top; const nodes = treeViewElement.querySelectorAll(".dx-treeview-node"); for(let i = 0; i < nodes.length; i++) { const nodeTopPosition = nodes[i].getBoundingClientRect().top; if(nodeTopPosition >= treeViewTopPosition) { return nodes[i]; } } return null; } } @NgModule({ imports: [ BrowserModule, DxTreeViewModule, DxSortableModule ], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule { } platformBrowserDynamic().bootstrapModule(AppModule);
::ng-deep .form { display: flex; } ::ng-deep .form>div { display: inline-block; vertical-align: top; } ::ng-deep #treeviewDriveC, ::ng-deep #treeviewDriveD { margin-top: 10px; } ::ng-deep .drive-header { min-height: auto; padding: 0px; cursor: default; } ::ng-deep .drive-header .dx-icon { margin-top: -4px; } ::ng-deep .drive-panel { padding: 20px 30px; font-size: 115%; font-weight: bold; border-right: 1px solid rgba(165, 165, 165, 0.4); height: 100%; } ::ng-deep .drive-panel:last-of-type { border-right: none; } ::ng-deep .dx-treeview-item { position: relative; left: -2px; }
import { Injectable } from '@angular/core'; export class FileSystemItem { id: string; parentId?: string; name: string; isDirectory: boolean; expanded?: boolean; } const itemsDriveD: FileSystemItem[] = []; const itemsDriveC: FileSystemItem[] = [{ id: '1', name: 'Documents', isDirectory: true, expanded: true }, { id: '2', parentId: '1', name: 'Projects', isDirectory: true, expanded: true }, { id: '3', parentId: '2', name: 'About.rtf', isDirectory: false, expanded: true }, { id: '4', parentId: '2', name: 'Passwords.rtf', isDirectory: false, expanded: true }, { id: '5', parentId: '2', name: 'About.xml', isDirectory: false, expanded: true }, { id: '6', parentId: '2', name: 'Managers.rtf', isDirectory: false, expanded: true }, { id: '7', parentId: '2', name: 'ToDo.txt', isDirectory: false, expanded: true }, { id: '8', name: 'Images', isDirectory: true, expanded: true }, { id: '9', parentId: '8', name: 'logo.png', isDirectory: false, expanded: true }, { id: '10', parentId: '8', name: 'banner.gif', isDirectory: false, expanded: true }, { id: '11', name: 'System', isDirectory: true, expanded: true }, { id: '12', parentId: '11', name: 'Employees.txt', isDirectory: false, expanded: true }, { id: '13', parentId: '11', name: 'PasswordList.txt', isDirectory: false, expanded: true }, { id: '14', name: 'Description.rtf', isDirectory: false, expanded: true }, { id: '15', name: 'Description.txt', isDirectory: false, expanded: true }]; @Injectable() export class Service { getItemsDriveC(): FileSystemItem[] { return itemsDriveC; } getItemsDriveD(): FileSystemItem[] { return itemsDriveD; } }
// In real applications, you should not transpile code in the browser. You can see how to create your own application with Angular and DevExtreme here: // https://js.devexpress.com/Documentation/Guide/Angular_Components/Getting_Started/Create_a_DevExtreme_Application/ System.config({ transpiler: 'ts', typescriptOptions: { module: "system", emitDecoratorMetadata: true, experimentalDecorators: true }, meta: { 'typescript': { "exports": "ts" }, }, paths: { 'npm:': 'https://unpkg.com/' }, map: { 'ts': 'npm:plugin-typescript@8.0.0/lib/plugin.js', 'typescript': 'npm:typescript@3.4.5/lib/typescript.js', '@angular': 'npm:@angular', 'tslib': 'npm:tslib/tslib.js', 'rxjs': 'npm:rxjs', 'devextreme': 'npm:devextreme@20.1', 'jszip': 'npm:jszip@3.1.3/dist/jszip.min.js', 'quill': 'npm:quill@1.3.7/dist/quill.js', 'devexpress-diagram': 'npm:devexpress-diagram@1.0.9', 'devexpress-gantt': 'npm:devexpress-gantt@1.0.7', 'devextreme-angular': 'npm:devextreme-angular@20.1' }, packages: { 'app': { main: './app.component.ts', defaultExtension: 'ts' }, 'devextreme': { defaultExtension: 'js' }, 'devextreme/events/utils': { main: 'index' }, 'devextreme/events': { main: 'index' }, }, packageConfigPaths: [ "npm:*/package.json", "npm:@angular/*/package.json", "npm:@angular/common/*/package.json", "npm:rxjs/operators/package.json", "npm:devextreme-angular@20.1/*/package.json", "npm:devextreme-angular@20.1/ui/*/package.json", ] });
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>DevExtreme Demo</title> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> <link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/20.1.6/css/dx.common.css" /> <link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/20.1.6/css/dx.light.css" /> <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script> <script src="https://unpkg.com/zone.js@0.10.2/dist/zone.js"></script> <script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script> <script src="https://unpkg.com/systemjs@0.21.3/dist/system.js"></script> <script src="config.js"></script> <script> System.import('app').catch(console.error.bind(console)); </script> </head> <body class="dx-viewport"> <div class="demo-container"> <demo-app>Loading...</demo-app> </div> </body> </html>