# Drag &amp; drop

**Drag and drop** interactions enable users to select items and dragging them and dropping them in a different location.

## Usage

This interaction allows users to directly manipulate the interface and can be applied to various use cases, such as reorganizing elements, transferring objects between areas, or altering the layout.

![Drag and drop](<../images/drag-and-drop.png>)

Drag and drop interactions can be initiated implicitly or explicitly:

- **Implicit drag-and-drop**: The user can directly drag and move an object to a desired position.
- **Explicit drag-and drop**: To initiate dragging, the user must first enter an edit-mode or navigate to a dedicated setup page. Once this action is completed, the user gains the ability to perform CRUD operations (create, read, update, and delete).

### When to use

- **Move**: Transferring data between different areas on the screen, such as moving or assigning items (e.g. [file uploader](<https://element.siemens.io/components/forms-inputs/file-uploader/>)).
- **Reorder**: Reordering items in a list (e.g. [column selection dialog](<https://element.siemens.io/components/layout-navigation/modals/>)).
- **Arrange**: To place and size objects in their desired positions on a canvas, like graphical editors or [flexible dashboards](<https://element.siemens.io/components/dashboards/flexible-dashboards/>).

### Best practices

- Drag-and-drop interactions can be imprecise and inefficient. Consider whether this type of interaction is the most suitable for the user's needs.
- Ensure there's a keyboard-accessible alternative to perform the same tasks, for users who cannot use a mouse or touch screen.
- Ensure that drop targets are large enough to minimize the need for precise movements.
- Keep the dragging distance short.

## Design

### Common signifiers

Signifiers are visual cues consistently applied to drag-and-drop interactions. There are two types of visual signifiers for grabbability: grab-handle icons and cursor changes.

**Grab handle** icons communicate that drag–and–drop is available and provide a safe target to click and drag without activating other nearby controls. **Cursor changes** signal in mouse-driven interfaces that drag–and–drop is available.

![Drag and drop - handle icons](<../images/drag-and-drop-signifiers.png>)

### States

- Default state: The initial state before any interaction begins. Items are displayed normally.
- Hover state: Activated when the cursor moves over a draggable item. The cursor changes to indicate draggability.
- Grabbed (click and hold): Initiated when the user clicks on the item and holds down the mouse button, signaling the intention to drag.
- In motion (dragging): The state when the item is being dragged across the screen to a new location. During this state, apply an elevation of 2 to the item that's being dragged.

![Drag and drop - states](<../images/drag-and-drop-states.png>)

Draggable items can be implicitly (no drag icon) or explicitly (with drag icon) identified. Add a drag icon when draggability isn't obvious. Avoid it if draggability is clear or the item is visually complex.

In scenarios where the source of a draggable item should be retained, as in assigning patterns where an item can be used multiple times, indicate they are in transition by lowering the opacity of the source item.

![Drag and drop ](<../images/drag-and-drop-source-item.png>)

### Drop target

The drop target can be either **dynamic** or **static**.

**Dynamic drop** targets adjust according to the item being moved, providing immediate feedback on its new position.

Dynamic drop targets are utilized in reorder or transferring interactions, such as in a list. They're also used in placement interactions, for positioning objects without constraints on a canvas, as seen in graphical editors or [flexible dashboards](<https://element.siemens.io/components/dashboards/flexible-dashboards/>).

![Drag and drop - reorder](<../images/drag-and-drop-reorder.png>)

**Static drop targets**, featuring a fixed drop area, are primarily utilized in assigning interactions. These interactions involve linking an object to a specific property, category, group, or attribute.

![Drag and drop - assign](<../images/drag-and-drop-assign.png>)

In cases with a designated dropzone, such as in a [file uploader](<https://element.siemens.io/components/forms-inputs/file-uploader/>), the predefined area for receiving items is clearly marked to ensure users can easily identify the target destination.

![Drag and drop - zone based](<../images/drag-and-drop-zone-based.png>)

#### Drag &amp; Drop in tree

Drag and drop in [tree structures](<https://element.siemens.io/components/lists-tables-trees/tree-view/>) allows users to rearrange or nest nodes. A position marker shows where nodes can be inserted, and potential parent nodes highlight when they can accept a nested node.

**Be mindful of these interactions, as they can be imprecise and may lead to conflicts in hierarchy management.**

![Drag and drop ](<../images/drag-and-drop-tree.png>)

### Accessibility considerations

**Always provide a keyboard-accessible alternative** to perform the same tasks, for users who cannot use a mouse or touch screen. Consider implementing keyboard-navigable context menus offering options like 'Move up', 'Move down', or 'Assign to', mirroring drag-and-drop interaction capabilities.

![Drag and drop - accesibility](<../images/drag-and-drop-accesible.png>)

Alternatively, implement these interactions using keyboard shortcuts, such as `ALT+Arrow` keys. To assist screen reader users, provide descriptions of these shortcuts either through visually hidden text, or by announcing the shortcuts within the corresponding context menu items.

*Note: Applications will have to implement these accessibility alternatives based on their use case. Element does not provide them by default.*

## Code

Element recommends to use Angular CDK's [drag and drop API](<https://material.angular.io/cdk/drag-drop/overview>) however there are certain use cases where CDK drag and drop APIs don't fit. For example:

- **File uploading using drag and drop:** In this case we recommend to use our [file uploader](<https://element.siemens.io/components/forms-inputs/file-uploader/>) component which internally use HTML5 drag and drop API for this purpose.
- **Configurable dashboard widgets:** We recommend to use our [flexible dashboard](<https://element.siemens.io/components/dashboards/flexible-dashboards/>) which is based on [gridstack](<https://gridstackjs.com/>).

Add `drop-line-placeholder` to a destination `cdkDropList` to show an insertion line instead of the default filled placeholder. Tree view items apply this style to their placeholders automatically.

### Usage

#### List

#### Example

##### List

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import {
  CdkDragDrop,
  DragDropModule,
  moveItemInArray,
  transferArrayItem
} from '@angular/cdk/drag-drop';
import { CdkListbox, CdkOption } from '@angular/cdk/listbox';
import { CdkContextMenuTrigger, CdkMenuModule } from '@angular/cdk/menu';
import { Component, signal, viewChildren } from '@angular/core';
import { form, FormField } from '@angular/forms/signals';
import { provideSiFormFieldConfig, SiFormFieldComponent } from '@siemens/element-ng/form';
import { SiMenuModule } from '@siemens/element-ng/menu';

@Component({
  selector: 'app-sample',
  imports: [
    DragDropModule,
    CdkListbox,
    CdkOption,
    SiMenuModule,
    CdkContextMenuTrigger,
    CdkMenuModule,
    FormField,
    SiFormFieldComponent
  ],
  templateUrl: './drag-drop.html',
  providers: [provideSiFormFieldConfig()]
})
export class SampleComponent {
  protected readonly useDropLine = signal(false);
  protected readonly useDropLineField = form(this.useDropLine);

  protected listOne = [
    'Cras justo odio',
    'Dapibus ac facilisis in',
    'Morbi leo risus',
    'Porta ac consectetur ac',
    'Vestibulum at eros'
  ];

  protected listTwo = [
    'Buy groceries: milk, bread, eggs, and cheese.',
    'Weekend tasks: clean the house, do laundry, and mow the lawn.',
    'Packing list: passport, toothbrush, sunscreen, and camera.',
    'Project steps: research, planning, execution, and review.',
    'Shopping list: apples, oranges, bananas, and grapes.',
    'Daily routine: wake up, exercise, breakfast, and work.'
  ];

  protected readonly itemInClipboard = signal<
    { item: string; list: string[]; index: number } | undefined
  >(undefined);

  private readonly cdkOptionsListOne = viewChildren('listOneItem', { read: CdkOption });
  private readonly cdkOptionsListTwo = viewChildren('listTwoItem', { read: CdkOption });

  protected itemDropped(event: CdkDragDrop<any>): void {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }
  /**
   * Moves an item within a list to a new index.
   * This is just for demo to show how to handle keyboard interactions.
   * You may need to consider appropriate screen reader announcement as well while moving items.
   */
  protected moveWithinList(items: string[], previousIndex: number, currentIndex: number): void {
    if (currentIndex >= 0 && currentIndex < items.length) {
      moveItemInArray(items, previousIndex, currentIndex);
      if (items === this.listOne) {
        this.cdkOptionsListOne()[currentIndex].focus();
      } else {
        this.cdkOptionsListTwo()[currentIndex].focus();
      }
    }
  }

  protected cutItem(data: { item: string; list: string[]; index: number }): void {
    this.itemInClipboard.set(data);
  }

  protected pasteItem(data: { item: string; list: string[]; index: number }): void {
    if (data.list === this.itemInClipboard()?.list) {
      moveItemInArray(data.list, this.itemInClipboard()!.index!, data.index + 1);
    } else {
      transferArrayItem(
        this.itemInClipboard()!.list,
        data.list,
        this.itemInClipboard()!.index,
        data.index + 1
      );
    }
    this.itemInClipboard.set(undefined);
  }

  protected keydown(
    event: KeyboardEvent,
    data: { item: string; list: string[]; index: number }
  ): void {
    if (event.metaKey && event.key === 'x' && data.item !== 'Morbi leo risus') {
      this.cutItem(data);
    } else if (event.metaKey && event.key === 'v') {
      this.pasteItem(data);
    }
  }
}
```

Template:

```html
<div class="p-5">
  <h2>Reorder within list or Move between list</h2>
  <si-form-field class="form-switch mb-5" label="Use drop line placeholder">
    <input type="checkbox" class="form-check-input" role="switch" [formField]="useDropLineField" />
  </si-form-field>
  <div class="d-flex gap-8">
    <ul
      #cdkListOne="cdkDropList"
      aria-label="List one"
      aria-keyshortcuts="Alt+ArrowUp Alt+ArrowDown Cmd+X Cmd+V"
      class="list-group list-group-flush"
      cdkListbox
      cdkDropList
      [class.drop-line-placeholder]="useDropLine()"
      [cdkDropListConnectedTo]="cdkListTwo"
      [cdkDropListData]="listOne"
      [tabindex]="0"
      (cdkDropListDropped)="itemDropped($event)"
    >
      @for (item of listOne; track $index) {
        <li
          #listOneItem
          class="list-group-item list-group-item-action"
          cdkDrag
          [cdkOption]="item"
          [cdkDragData]="item"
          [cdkDragDisabled]="item === 'Morbi leo risus'"
          [cdkContextMenuTriggerFor]="contextMenu"
          [cdkContextMenuTriggerData]="{ $implicit: { item: item, list: listOne, index: $index } }"
          [style.opacity]="itemInClipboard()?.item === item ? 0.7 : 1"
          (keydown)="keydown($event, { item: item, list: listOne, index: $index })"
          (keydown.alt.arrowUp)="moveWithinList(listOne, $index, $index - 1)"
          (keydown.alt.arrowDown)="moveWithinList(listOne, $index, $index + 1)"
          >{{ item }}</li
        >
      }
    </ul>

    <ul
      #cdkListTwo="cdkDropList"
      aria-label="List two"
      aria-keyshortcuts="Alt+ArrowUp Alt+ArrowDown Cmd+X Cmd+V"
      class="list-group list-group-flush"
      cdkListbox
      cdkDropList
      [class.drop-line-placeholder]="useDropLine()"
      [cdkDropListData]="listTwo"
      [cdkDropListConnectedTo]="cdkListOne"
      (cdkDropListDropped)="itemDropped($event)"
    >
      @for (item of listTwo; track $index) {
        <li
          #listTwoItem
          class="list-group-item list-group-item-action"
          cdkDrag
          [cdkOption]="item"
          [cdkContextMenuTriggerFor]="contextMenu"
          [cdkContextMenuTriggerData]="{ $implicit: { item: item, list: listTwo, index: $index } }"
          [style.opacity]="itemInClipboard()?.item === item ? 0.7 : 1"
          (keydown)="keydown($event, { item: item, list: listTwo, index: $index })"
          (keydown.alt.arrowUp)="moveWithinList(listTwo, $index, $index - 1)"
          (keydown.alt.arrowDown)="moveWithinList(listTwo, $index, $index + 1)"
          >{{ item }}</li
        >
      }
    </ul>
  </div>
</div>

<ng-template #contextMenu let-data>
  <si-menu>
    <si-menu-header>Actions</si-menu-header>
    <si-menu-item [disabled]="data.item === 'Morbi leo risus'" (triggered)="cutItem(data)"
      >Cut this item to move</si-menu-item
    >
    <si-menu-item [disabled]="!itemInClipboard()" (triggered)="pasteItem(data)"
      >Paste below this item</si-menu-item
    >
  </si-menu>
</ng-template>
```

##### Cards

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import {
  CdkDragDrop,
  DragDropModule,
  moveItemInArray,
  transferArrayItem
} from '@angular/cdk/drag-drop';
import { CdkListbox, CdkOption } from '@angular/cdk/listbox';
import { Component } from '@angular/core';
import { SiCardComponent } from '@siemens/element-ng/card';
import { SiIconModule } from '@siemens/element-ng/icon';
import { SiMenuModule } from '@siemens/element-ng/menu';

@Component({
  selector: 'app-sample',
  imports: [DragDropModule, CdkListbox, CdkOption, SiCardComponent, SiIconModule, SiMenuModule],
  templateUrl: './drag-drop-cards.html',
  styles: `
    .card-size {
      block-size: 150px;
      inline-size: 250px;
    }
    .card-body:hover {
      cursor: auto;
    }
  `
})
export class SampleComponent {
  protected cards = [
    {
      heading: `Natural Gas Usage`,
      text: `Some quick example text to build on the card title and make up the bulk of the card's
  content.`
    },
    {
      heading: `FS20`,
      text: `Some quick example text to build on the card title and make up the bulk of the card's
  content.`,
      dragDisabled: true
    },
    {
      heading: `Overflows`,
      text: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum nec ornare nunc,
  quis feugiat ex. Vivamus mollis nisi at dapibus vehicula. Curabitur dui ante, interdum
  pharetra hendrerit vel, efficitur in erat. Phasellus porttitor molestie orci, vel
  consectetur ipsum commodo eget. Pellentesque ac gravida mi, id vehicula purus. Sed
  egestas nisl est, eget faucibus velit hendrerit vulputate. Aenean et pretium enim, in
  facilisis est. Nam luctus felis ut auctor sollicitudin. Donec elementum nec lorem vitae
  scelerisque. Mauris elementum metus diam, sit amet ornare mi rhoncus sit amet. Nulla
  semper scelerisque molestie. Cras et purus et nisi interdum maximus sed et leo. Mauris
  bibendum hendrerit nunc, sed malesuada augue.`
    },
    {
      heading: `Oil Usage`,
      text: `Some quick example text to build on the card title and make up the bulk of the card's
  content.`
    },
    {
      heading: `Water Usage`,
      text: `Some quick example text to build on the card title and make up the bulk of the card's
  content.`
    }
  ];

  protected itemDropped(event: CdkDragDrop<any>): void {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }
}
```

Template:

```html
<div class="p-5">
  <h2>Horizontal wrapping cards</h2>
  <div>
    <div
      class="d-flex flex-wrap gap-4"
      cdkListbox
      cdkDropList
      cdkDropListOrientation="mixed"
      cdkListboxOrientation="horizontal"
      [cdkDropListData]="cards"
      (cdkDropListDropped)="itemDropped($event)"
    >
      @for (item of cards; track $index) {
        <si-card
          #card
          cdkDrag
          class="card-size"
          [cdkOption]="item"
          [heading]="item.heading"
          [cdkDragDisabled]="item?.dragDisabled"
        >
          <p class="card-body card-text overflow-auto" body>
            {{ item.text }}
          </p>
        </si-card>
      }
    </div>
  </div>
  <hr />
  <h2>Free drag</h2>
  <div>
    <div class="card h-100" style="width: 250px" cdkDrag>
      <div class="card-header">Drag without boundries</div>
      <div class="card-body">
        <p class="card-text">This card can be dragged anywhere on screen.</p>
      </div>
    </div>
  </div>
</div>
```

#### Tree with different drag and drop use cases

#### Example

##### Moving between trees

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { CdkDrag, CdkDragDrop, CdkDropList, DragDropModule } from '@angular/cdk/drag-drop';
import { Component } from '@angular/core';
import {
  reorderTreeItem,
  SiTreeViewComponent,
  SiTreeViewItemComponent,
  SiTreeViewItemDirective,
  transferTreeItem,
  TreeItem
} from '@siemens/element-ng/tree-view';

import { treeItemsUnderMaintenance, treeItemsWithCompletedMaintenance } from './tree-items';

@Component({
  selector: 'app-sample',
  imports: [SiTreeViewComponent, SiTreeViewItemComponent, SiTreeViewItemDirective, DragDropModule],
  templateUrl: './si-tree-view-drag-drop-move.html',
  host: { class: 'p-5' }
})
// NOTE: This example is to demonstrate CDK drag drop API capabilities with SiTreeViewItemNextComponent
// and it is not yet production ready.
export class SampleComponent {
  protected moveTreeOneList = treeItemsUnderMaintenance;
  protected moveTreeTwoList = treeItemsWithCompletedMaintenance;

  protected itemDroppedTreeOne(event: CdkDragDrop<TreeItem[]>): void {
    const targetIndex =
      event.currentIndex < event.previousIndex ? event.currentIndex - 1 : event.currentIndex;

    const dragItem = event.container.data[event.previousIndex];
    const targetItem = event.container.data[targetIndex];

    if (!this.isValidMove(dragItem, targetItem)) {
      return;
    }
    const updatedTree = [...reorderTreeItem(this.moveTreeOneList, event)];
    this.moveTreeOneList = updatedTree;
  }

  protected itemDroppedTreeTwo(event: CdkDragDrop<any>): void {
    let targetIndex = event.currentIndex - 1;
    if (event.container === event.previousContainer) {
      targetIndex =
        event.currentIndex < event.previousIndex ? event.currentIndex - 1 : event.currentIndex;
    }

    const dragItem = event.previousContainer.data[event.previousIndex];
    const targetItem = event.container.data[targetIndex];

    if (!this.isValidMove(dragItem, targetItem)) {
      return;
    }
    if (event.container === event.previousContainer) {
      const updatedTree = [...reorderTreeItem(this.moveTreeTwoList, event)];
      this.moveTreeTwoList = updatedTree;
    } else {
      const updatedTrees = transferTreeItem(
        this.moveTreeOneList,
        this.moveTreeTwoList,
        event,
        true
      );
      this.moveTreeOneList = [...updatedTrees.sourceTree];
      this.moveTreeTwoList = [...updatedTrees.targetTree];
    }
  }

  private isValidMove(source: TreeItem, target: TreeItem): boolean {
    if (source.level === 0 && (!target || (target.level === 0 && !(target.state === 'expanded')))) {
      return true;
    } else {
      if (target && source.state === 'leaf') {
        // if target is leaf then item will be dropped as sibling to that target
        if (target.state === 'leaf') {
          return source.parent?.customData.locatorId === target.parent?.customData.locatorId;
        }
        // item will be dropped as a children to the target item
        // in case of expanded target
        else if (target.state === 'expanded') {
          return source.parent?.customData.locatorId === target.customData.locatorId;
        }
      } else {
        if (target?.customData) {
          return source.customData.locatorId === target.customData.locatorId;
        }
      }
      return false;
    }
  }

  protected allowDrop(dragItem: CdkDrag<TreeItem>, dropList: CdkDropList): boolean {
    return dragItem.data.level === 2;
  }
}
```

Template:

```html
<h3>Moving between trees</h3>
<p
  >You can move equipment within same building in same faulty equipment list or move into
  operational equipment list.</p
>
<div class="d-flex h-100" style="width: 600px">
  <div>
    <h4>Faulty equipment list</h4>

    <si-tree-view
      #moveTreeOne
      ariaLabel="Company locations"
      class="me-8"
      style="width: 300px; height: 500px"
      [enableDataField1]="true"
      [enableSelection]="false"
      [items]="moveTreeOneList"
      [flatTree]="false"
    >
      <div
        cdkDropList
        [cdkDropListConnectedTo]="treeTwoList"
        [cdkDropListData]="moveTreeOne.dropListItems"
        (cdkDropListDropped)="itemDroppedTreeOne($event)"
      >
        <ng-template let-item="treeItem" siTreeViewItem>
          <si-tree-view-item cdkDrag [cdkDragDisabled]="item.level === 0" [cdkDragData]="item">
            <si-tree-view-item *cdkDragPreview />
          </si-tree-view-item>
        </ng-template>
      </div>
    </si-tree-view>
  </div>
  <div>
    <h4>Operational equipment list</h4>

    <si-tree-view
      #moveTreeTwo
      ariaLabel="Another company locations"
      style="width: 300px; height: 500px"
      [enableDataField1]="true"
      [enableSelection]="true"
      [items]="moveTreeTwoList"
      [flatTree]="false"
    >
      <div
        #treeTwoList="cdkDropList"
        cdkDropList
        [cdkDropListData]="moveTreeTwo.dropListItems"
        [cdkDropListEnterPredicate]="allowDrop"
        (cdkDropListDropped)="itemDroppedTreeTwo($event)"
      >
        <ng-template let-item="treeItem" siTreeViewItem>
          <si-tree-view-item cdkDrag [cdkDragDisabled]="item.level === 0">
            <si-tree-view-item *cdkDragPreview />
          </si-tree-view-item>
        </ng-template>
      </div>
    </si-tree-view>
  </div>
</div>
```

##### Copying between trees

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { CdkDrag, CdkDragDrop, DragDropModule } from '@angular/cdk/drag-drop';
import { Component } from '@angular/core';
import {
  reorderTreeItem,
  SiTreeViewComponent,
  SiTreeViewItemComponent,
  SiTreeViewItemDirective,
  transferTreeItem,
  TreeItem
} from '@siemens/element-ng/tree-view';

const templateCatalog: TreeItem[] = [
  {
    label: 'HVAC',
    icon: 'element-air',
    state: 'expanded',
    customData: { locatorId: 'cat-hvac' },
    children: [
      { label: 'Temperature sensor', icon: 'element-temperature', state: 'leaf' },
      { label: 'HVAC unit', icon: 'element-vrf', state: 'leaf' },
      { label: 'Air quality sensor', icon: 'element-indoor-air-quality', state: 'leaf' }
    ]
  },
  {
    label: 'Lighting',
    icon: 'element-sun',
    state: 'expanded',
    customData: { locatorId: 'cat-lighting' },
    children: [
      { label: 'LED panel', icon: 'element-light', state: 'leaf' },
      { label: 'Motion sensor', icon: 'element-occupancy-sensor', state: 'leaf' }
    ]
  },
  {
    label: 'Security',
    icon: 'element-lock',
    state: 'expanded',
    customData: { locatorId: 'cat-security' },
    children: [
      { label: 'Security camera', icon: 'element-security-cam', state: 'leaf' },
      { label: 'Door sensor', icon: 'element-door', state: 'leaf' }
    ]
  }
];

const siteConfiguration: TreeItem[] = [
  {
    label: 'Headquarters Zug',
    icon: 'element-project',
    state: 'expanded',
    customData: { locatorId: 'site-zug' },
    children: [
      {
        label: 'Building A',
        icon: 'element-building',
        state: 'expanded',
        customData: { locatorId: 'site-zug-a' },
        children: [{ label: 'Temperature sensor', icon: 'element-temperature', state: 'leaf' }]
      },
      {
        label: 'Building B',
        icon: 'element-building',
        state: 'expanded',
        customData: { locatorId: 'site-zug-b' },
        children: [{ label: 'LED panel', icon: 'element-light', state: 'leaf' }]
      }
    ]
  },
  {
    label: 'Office Milano',
    icon: 'element-project',
    state: 'expanded',
    customData: { locatorId: 'site-milano' },
    children: [
      {
        label: 'Building 1',
        icon: 'element-building',
        state: 'expanded',
        customData: { locatorId: 'site-milano-1' },
        children: [{ label: 'Security camera', icon: 'element-security-cam', state: 'leaf' }]
      }
    ]
  }
];

@Component({
  selector: 'app-sample',
  imports: [SiTreeViewComponent, SiTreeViewItemComponent, SiTreeViewItemDirective, DragDropModule],
  templateUrl: './si-tree-view-drag-drop-copy.html',
  host: { class: 'p-5' }
})
// NOTE: This example is to demonstrate CDK drag drop API capabilities with SiTreeViewItemNextComponent
// and it is not yet production ready.
export class SampleComponent {
  protected catalogList = templateCatalog;
  protected siteList = siteConfiguration;

  protected itemDroppedOnSite(event: CdkDragDrop<TreeItem[]>): void {
    let targetIndex = event.currentIndex - 1;
    if (event.container === event.previousContainer) {
      targetIndex =
        event.currentIndex < event.previousIndex ? event.currentIndex - 1 : event.currentIndex;
    }

    const dragItem = event.previousContainer.data[event.previousIndex];
    const targetItem = event.container.data[targetIndex];

    if (!this.isValidDrop(dragItem, targetItem)) {
      return;
    }
    if (event.container === event.previousContainer) {
      this.siteList = [...reorderTreeItem(this.siteList, event)];
    } else {
      const updated = transferTreeItem(this.catalogList, this.siteList, event, false);
      this.catalogList = [...updated.sourceTree];
      this.siteList = [...updated.targetTree];
    }
  }

  protected allowDropOnSite(dragItem: CdkDrag<TreeItem>): boolean {
    // Only device templates (leaves) from the catalog can be copied
    return dragItem.data.state === 'leaf';
  }

  private isValidDrop(source: TreeItem, target: TreeItem): boolean {
    if (!target || source.state !== 'leaf') {
      return false;
    }
    // Drop into a building (expanded level-1 node) or next to a device inside one
    if (target.state === 'expanded' && target.level === 1) {
      return true;
    }
    if (target.state === 'leaf' && target.level === 2) {
      return true;
    }
    return false;
  }
}
```

Template:

```html
<h3>Provisioning sites from a device template catalog</h3>
<p
  >Drag a device template from the catalog onto a building in the site configuration to provision
  it. Templates remain in the catalog so the same device type can be reused across multiple
  buildings.</p
>
<div class="d-flex h-100" style="width: 600px">
  <div>
    <h4>Device template catalog</h4>

    <si-tree-view
      #catalog
      ariaLabel="Device template catalog"
      class="me-8"
      style="width: 300px; height: 500px"
      [enableSelection]="false"
      [items]="catalogList"
      [flatTree]="false"
    >
      <div
        cdkDropList
        cdkDropListHasAnchor
        cdkDropListSortingDisabled
        [cdkDropListConnectedTo]="siteDropList"
        [cdkDropListData]="catalog.dropListItems"
      >
        <ng-template let-item="treeItem" siTreeViewItem>
          <si-tree-view-item cdkDrag [cdkDragDisabled]="item.state !== 'leaf'" [cdkDragData]="item">
            <si-tree-view-item *cdkDragPreview />
          </si-tree-view-item>
        </ng-template>
      </div>
    </si-tree-view>
  </div>
  <div>
    <h4>Site configuration</h4>

    <si-tree-view
      #site
      ariaLabel="Site configuration"
      style="width: 300px; height: 500px"
      [enableSelection]="true"
      [items]="siteList"
      [flatTree]="false"
    >
      <div
        #siteDropList="cdkDropList"
        cdkDropList
        [cdkDropListData]="site.dropListItems"
        [cdkDropListEnterPredicate]="allowDropOnSite"
        (cdkDropListDropped)="itemDroppedOnSite($event)"
      >
        <ng-template let-item="treeItem" siTreeViewItem>
          <si-tree-view-item cdkDrag cdkDragDisabled>
            <si-tree-view-item *cdkDragPreview />
          </si-tree-view-item>
        </ng-template>
      </div>
    </si-tree-view>
  </div>
</div>
```

##### Copying from a list to a tree

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { CdkDrag, CdkDragDrop, DragDropModule } from '@angular/cdk/drag-drop';
import { Component } from '@angular/core';
import {
  SiTreeViewComponent,
  SiTreeViewItemComponent,
  SiTreeViewItemDirective,
  TreeItem
} from '@siemens/element-ng/tree-view';

const templateCatalog: TreeItem[] = [
  { label: 'Temperature sensor', icon: 'element-temperature', state: 'leaf' },
  { label: 'HVAC unit', icon: 'element-vrf', state: 'leaf' },
  { label: 'Air quality sensor', icon: 'element-indoor-air-quality', state: 'leaf' },
  { label: 'LED panel', icon: 'element-light', state: 'leaf' },
  { label: 'Motion sensor', icon: 'element-occupancy-sensor', state: 'leaf' },
  { label: 'Security camera', icon: 'element-security-cam', state: 'leaf' },
  { label: 'Door sensor', icon: 'element-door', state: 'leaf' }
];

const siteConfiguration: TreeItem[] = [
  {
    label: 'Headquarters Zug',
    icon: 'element-project',
    state: 'expanded',
    customData: { locatorId: 'site-zug' },
    children: [
      {
        label: 'Building A',
        icon: 'element-building',
        state: 'expanded',
        customData: { locatorId: 'site-zug-a' },
        children: [{ label: 'Temperature sensor', icon: 'element-temperature', state: 'leaf' }]
      },
      {
        label: 'Building B',
        icon: 'element-building',
        state: 'expanded',
        customData: { locatorId: 'site-zug-b' },
        children: [{ label: 'LED panel', icon: 'element-light', state: 'leaf' }]
      }
    ]
  },
  {
    label: 'Office Milano',
    icon: 'element-project',
    state: 'expanded',
    customData: { locatorId: 'site-milano' },
    children: [
      {
        label: 'Building 1',
        icon: 'element-building',
        state: 'expanded',
        customData: { locatorId: 'site-milano-1' },
        children: [{ label: 'Security camera', icon: 'element-security-cam', state: 'leaf' }]
      }
    ]
  }
];

@Component({
  selector: 'app-sample',
  imports: [SiTreeViewComponent, SiTreeViewItemComponent, SiTreeViewItemDirective, DragDropModule],
  templateUrl: './si-tree-view-drag-drop-copy-from-list.html',
  host: { class: 'p-5' }
})
export class SampleComponent {
  protected catalogList = templateCatalog;
  protected siteList = siteConfiguration;

  protected itemDroppedOnSite(event: CdkDragDrop<TreeItem[]>): void {
    if (event.container === event.previousContainer) {
      return;
    }

    const dragItem = event.previousContainer.data[event.previousIndex];
    const targetItem = event.container.data[event.currentIndex - 1];

    if (!this.isValidDrop(dragItem, targetItem)) {
      return;
    }

    const parent = targetItem.state === 'expanded' ? targetItem : targetItem.parent;
    if (!parent) {
      return;
    }

    const siblings = parent.children ?? [];
    const index = targetItem.state === 'expanded' ? 0 : siblings.indexOf(targetItem) + 1;
    const copy = { ...structuredClone(dragItem), parent, level: (parent.level ?? 0) + 1 };
    parent.children = [...siblings.slice(0, index), copy, ...siblings.slice(index)];
    this.siteList = [...this.siteList];
  }

  protected allowDropOnSite(dragItem: CdkDrag<TreeItem>): boolean {
    // Only device templates (leaves) from the catalog can be copied
    return dragItem.data.state === 'leaf';
  }

  private isValidDrop(
    source: TreeItem | undefined,
    target: TreeItem | undefined
  ): target is TreeItem {
    if (!target || source?.state !== 'leaf') {
      return false;
    }
    // Drop into a building (expanded level-1 node) or next to a device inside one
    if (target.state === 'expanded' && target.level === 1) {
      return true;
    }
    if (target.state === 'leaf' && target.level === 2) {
      return true;
    }
    return false;
  }
}
```

Template:

```html
<h3>Provisioning sites from a device template catalog</h3>
<p
  >Drag a device template from the catalog onto a building in the site configuration to provision
  it. Templates remain in the catalog so the same device type can be reused across multiple
  buildings.</p
>
<div class="d-flex h-100" style="width: 600px">
  <div>
    <h4>Device template catalog</h4>

    <ul
      aria-label="Device template catalog"
      class="list-group list-group-flush me-8"
      style="width: 300px"
      cdkDropList
      cdkDropListHasAnchor
      cdkDropListSortingDisabled
      [cdkDropListConnectedTo]="siteDropList"
      [cdkDropListData]="catalogList"
    >
      @for (item of catalogList; track item.label) {
        <li class="catalog-item list-group-item" cdkDrag [cdkDragData]="item">
          <span>{{ item.label }}</span>
        </li>
      }
    </ul>
  </div>
  <div>
    <h4>Site configuration</h4>

    <si-tree-view
      #site
      ariaLabel="Site configuration"
      style="width: 300px; height: 500px"
      [enableSelection]="true"
      [items]="siteList"
      [flatTree]="false"
    >
      <div
        #siteDropList="cdkDropList"
        class="drop-line-placeholder"
        cdkDropList
        [cdkDropListData]="site.dropListItems"
        [cdkDropListEnterPredicate]="allowDropOnSite"
        (cdkDropListDropped)="itemDroppedOnSite($event)"
      >
        <ng-template let-item="treeItem" siTreeViewItem>
          <si-tree-view-item cdkDrag cdkDragDisabled>
            <si-tree-view-item *cdkDragPreview />
          </si-tree-view-item>
        </ng-template>
      </div>
    </si-tree-view>
  </div>
</div>
```

##### Reordering

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { CdkDragDrop, DragDropModule } from '@angular/cdk/drag-drop';
import { Component } from '@angular/core';
import {
  reorderTreeItem,
  SiTreeViewComponent,
  SiTreeViewItemComponent,
  SiTreeViewItemDirective,
  TreeItem
} from '@siemens/element-ng/tree-view';

import { treeItems } from './tree-items';

@Component({
  selector: 'app-sample',
  imports: [SiTreeViewComponent, SiTreeViewItemComponent, SiTreeViewItemDirective, DragDropModule],
  templateUrl: './si-tree-view-drag-drop-reorder.html',
  host: { class: 'p-5' }
})
// NOTE: This example is to demonstrate CDK drag drop API capabilities with SiTreeViewItemNextComponent
// and it is not yet production ready.
export class SampleComponent {
  treeItems: TreeItem[] = treeItems;

  itemDropped(event: CdkDragDrop<any>): void {
    const reorderedTree = [...reorderTreeItem(this.treeItems, event)];
    this.treeItems = reorderedTree;
  }
}
```

Template:

```html
<h3>Reordering within same tree</h3>
<si-tree-view
  #treeWithDrag
  ariaLabel="Company locations"
  style="width: 300px; height: 500px"
  [enableDataField1]="true"
  [enableSelection]="true"
  [items]="treeItems"
  [flatTree]="false"
>
  <div
    cdkDropList
    [cdkDropListData]="treeWithDrag.dropListItems"
    (cdkDropListDropped)="itemDropped($event)"
  >
    <ng-template siTreeViewItem>
      <si-tree-view-item cdkDrag>
        <si-tree-view-item *cdkDragPreview />
      </si-tree-view-item>
    </ng-template>
  </div>
</si-tree-view>
```

##### Assignment

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { CdkDrag, CdkDragDrop, CdkDropList, DragDropModule } from '@angular/cdk/drag-drop';
import { Component, inject } from '@angular/core';
import {
  SiTreeViewComponent,
  SiTreeViewItemComponent,
  SiTreeViewItemDirective,
  TreeItem
} from '@siemens/element-ng/tree-view';
import { LOG_EVENT } from '@siemens/live-preview';

import { treeItems } from './tree-items';

@Component({
  selector: 'app-sample',
  imports: [SiTreeViewComponent, SiTreeViewItemComponent, SiTreeViewItemDirective, DragDropModule],
  templateUrl: './si-tree-view-drag-drop-assign.html',
  host: { class: 'p-5' }
})
// NOTE: This example is to demonstrate CDK drag drop API capabilities with SiTreeViewItemNextComponent
// and it is not yet production ready.
export class SampleComponent {
  log = inject(LOG_EVENT);

  treeItems: TreeItem[] = treeItems;

  assignTreeOneList = this.createDynamicTree(structuredClone(this.treeItems), 'Assign Tree One');

  assignTreeTwoList = this.createDynamicTree(structuredClone(this.treeItems), 'Assign Tree Two');

  treeItemAssigned(event: CdkDragDrop<any>): void {
    this.log(
      `Assigned '${event.previousContainer.data[event.previousIndex].label}' to the '${
        event.container.data.label
      }'`
    );
  }

  allowDrop(dragItem: CdkDrag, dropList: CdkDropList): boolean {
    if (dropList.data.dataField1 === 'SI' && dragItem.data.dataField1 === 'GG') {
      return false;
    }
    return true;
  }

  createDynamicTree(tree: TreeItem[], label: string): TreeItem[] {
    tree.forEach(item => {
      item.label = `${label} ${item.label}`;
      if (item.children) {
        this.createDynamicTree(item.children, label);
      }
    });
    return tree;
  }
}
```

Template:

```html
<h3>Assign tree item to another tree item</h3>
<div class="d-flex h-100" cdkDropListGroup>
  <si-tree-view
    #assignTreeOne
    ariaLabel="Company locations"
    class="me-8"
    style="width: 300px; height: 500px"
    [enableDataField1]="true"
    [enableSelection]="true"
    [items]="assignTreeOneList"
    [flatTree]="false"
  >
    <div
      cdkDropList
      [cdkDropListSortingDisabled]="true"
      [cdkDropListData]="assignTreeOne.dropListItems"
    >
      <ng-template let-item="treeItem" siTreeViewItem>
        <si-tree-view-item cdkDrag [cdkDragData]="item">
          <si-tree-view-item *cdkDragPreview />
        </si-tree-view-item>
      </ng-template>
    </div>
  </si-tree-view>

  <si-tree-view
    #assignTreeTwo
    ariaLabel="Company locations"
    style="width: 300px; height: 500px"
    [enableDataField1]="true"
    [enableSelection]="true"
    [items]="assignTreeTwoList"
    [flatTree]="false"
  >
    <ng-template let-item="treeItem" siTreeViewItem>
      <si-tree-view-item
        #assignTwoItem
        cdkDropList
        class="droppable-container"
        [cdkDropListData]="item"
        [cdkDropListSortingDisabled]="true"
        [cdkDropListEnterPredicate]="allowDrop"
        (cdkDropListDropped)="treeItemAssigned($event)"
      />
    </ng-template>
  </si-tree-view>
</div>
```

### Datatable with reorderable rows

#### Example

Component:

```typescript
/**
 * Copyright (c) Siemens 2016 - 2026
 * SPDX-License-Identifier: MIT
 */
import { CdkDragDrop, DragDropModule, moveItemInArray } from '@angular/cdk/drag-drop';
import { DatePipe } from '@angular/common';
import { Component } from '@angular/core';
// eslint-disable-next-line no-restricted-imports
import { TranslatePipe } from '@ngx-translate/core';
import { elementMenu } from '@siemens/element-icons';
import { addIcons, SiIconComponent } from '@siemens/element-ng/icon';
import { DatatableRowDefDirective, NgxDatatableModule } from '@siemens/ngx-datatable';

@Component({
  selector: 'app-sample',
  imports: [
    NgxDatatableModule,
    DatatableRowDefDirective,
    DragDropModule,
    TranslatePipe,
    DatePipe,
    SiIconComponent
  ],
  templateUrl: './datatable-row-dragging.html',
  host: { class: 'p-5' }
})
export class SampleComponent {
  icons = addIcons({ elementMenu });
  taskData = [
    {
      id: 1,
      priority: 1,
      task: 'Complete project proposal',
      deadline: 'July 28, 2023',
      status: 'In Progress',
      assignee: 'John Smith',
      department: 'Marketing'
    },
    {
      id: 2,
      priority: 2,
      task: 'Review client feedback',
      deadline: 'July 30, 2023',
      status: 'Not Started',
      assignee: 'Sarah Johnson',
      department: 'Customer Relations'
    },
    {
      id: 3,
      priority: 3,
      task: 'Update documentation',
      deadline: 'August 2, 2023',
      status: 'Not Started',
      assignee: 'Michael Chen',
      department: 'Development'
    },
    {
      id: 4,
      priority: 4,
      task: 'Prepare presentation slides',
      deadline: 'August 5, 2023',
      status: 'Not Started',
      assignee: 'Emily Rodriguez',
      department: 'Marketing'
    },
    {
      id: 5,
      priority: 5,
      task: 'Schedule team meeting',
      deadline: 'July 27, 2023',
      status: 'Completed',
      assignee: 'David Wilson',
      department: 'Operations'
    }
  ];

  protected isCompletedRow(row: unknown): boolean {
    type TaskDataRow = (typeof this.taskData)[number];
    return (row as TaskDataRow).status === 'Completed';
  }

  protected drop(event: CdkDragDrop<any>): void {
    moveItemInArray(this.taskData, event.previousIndex, event.currentIndex);
    this.taskData = [...this.taskData.map((item, index) => ({ ...item, priority: index + 1 }))];
  }
}
```

Template:

```html
<div class="p-5 d-flex flex-column">
  <ngx-datatable
    #table
    cdkDropList
    class="table-element"
    siDatatableInteraction
    columnMode="force"
    [rows]="taskData"
    (cdkDropListDropped)="drop($event)"
  >
    <ngx-datatable-column maxWidth="50" sortable="false">
      <ng-template let-row="row" ngx-datatable-cell-template>
        <div cdkDragHandle class="d-flex align-items-center">
          <si-icon class="icon" [icon]="icons.elementMenu" />
        </div>
      </ng-template>
    </ngx-datatable-column>

    <ngx-datatable-column
      minWidth="200"
      sortable="false"
      [name]="'DATATABLE.HEADER.TASK' | translate"
    >
      <ng-template let-row="row" ngx-datatable-cell-template>
        <div>
          <span>{{ row.task }}</span>
        </div>
      </ng-template>
    </ngx-datatable-column>
    <ngx-datatable-column
      minWidth="100"
      sortable="false"
      [name]="'DATATABLE.HEADER.ASSIGNEE' | translate"
    >
      <ng-template let-row="row" ngx-datatable-cell-template>
        <div>
          <span>{{ row.assignee }}</span>
        </div>
      </ng-template>
    </ngx-datatable-column>
    <ngx-datatable-column
      minWidth="100"
      sortable="false"
      [name]="'DATATABLE.HEADER.STATUS' | translate"
    >
      <ng-template let-row="row" ngx-datatable-cell-template>
        <div>
          <span>{{ row.status }}</span>
        </div>
      </ng-template>
    </ngx-datatable-column>
    <ngx-datatable-column
      maxWidth="100"
      minWidth="100"
      sortable="false"
      [name]="'DATATABLE.HEADER.DUE-DATE' | translate"
    >
      <ng-template let-row="row" ngx-datatable-cell-template>
        <div>
          <span>{{ row.deadline | date }}</span>
        </div>
      </ng-template>
    </ngx-datatable-column>
    <ngx-datatable-column
      minWidth="150"
      sortable="false"
      [name]="'DATATABLE.HEADER.DEPARTMENT' | translate"
    >
      <ng-template let-row="row" ngx-datatable-cell-template>
        <div>
          <span>{{ row.department }}</span>
        </div>
      </ng-template>
    </ngx-datatable-column>

    <ngx-datatable-column
      maxWidth="150"
      minWidth="100"
      sortable="false"
      [name]="'DATATABLE.HEADER.PRIORITY' | translate"
    >
      <ng-template let-row="row" ngx-datatable-cell-template>
        <div>
          <span>{{ row.priority }}</span>
        </div>
      </ng-template>
    </ngx-datatable-column>

    <ng-template let-row="row" rowDef>
      <datatable-row-def
        cdkDrag
        cdkDragPreviewContainer="parent"
        preserveColumnWidthsOnClone
        [cdkDragDisabled]="isCompletedRow(row)"
      />
    </ng-template>
  </ngx-datatable>
</div>
```
