skip to content

With the Angular CDK's cdkDropList and cdkDrag directives, how do you make a playlist reorderable, and why would a dragged track snap back?

level: juniorimportance: must knowfreq 44%

answer

  1. who owns the array?
  2. the drop list's output event
  3. two indexes in the event
  4. an in-place array helper
  5. DOM restored after release

basics

~20 s

In the Angular CDK, put cdkDropList on the container and cdkDrag on each row, handle cdkDropListDropped by calling moveItemInArray with previousIndex and currentIndex. The CDK never reorders your array, so without that handler the row returns to its slot.

solid answer

~40 s

Import `CdkDropList` and `CdkDrag` from `@angular/cdk/drag-drop`, put `cdkDropList` on the playlist container and `cdkDrag` on each track row rendered by `@for`. While the user drags, the CDK shifts the other rows visually and shows a placeholder where the row would land. On release the list emits `cdkDropListDropped` with a `CdkDragDrop` event carrying `previousIndex` and `currentIndex`, and your handler calls `moveItemInArray(tracks, event.previousIndex, event.currentIndex)`. The CDK deliberately leaves your data alone and puts the dragged element back where it was in the DOM, so if nothing updates the array the template keeps the old order and the row snaps back. With a signal, copy the array, move the item in the copy and set it, because `moveItemInArray` mutates in place and returns nothing.

code

ts · 31 lines
ts
import {Component, signal} from '@angular/core';
import {CdkDrag, CdkDragDrop, CdkDropList, moveItemInArray} from '@angular/cdk/drag-drop';

interface Track { id: string; title: string; }

@Component({
  selector: 'app-playlist',
  imports: [CdkDropList, CdkDrag],
  template: `
    <ol cdkDropList (cdkDropListDropped)="drop($event)">
      @for (track of tracks(); track track.id) {
        <li cdkDrag>{{ track.title }}</li>
      }
    </ol>
  `,
})
export class Playlist {
  readonly tracks = signal<Track[]>([
    {id: 't1', title: 'Intro'},
    {id: 't2', title: 'Night Drive'},
    {id: 't3', title: 'Outro'},
  ]);

  drop(event: CdkDragDrop<Track[]>) {
    this.tracks.update(list => {
      const next = [...list];
      moveItemInArray(next, event.previousIndex, event.currentIndex);
      return next;
    });
  }
}

go deeper

for a junior

Recall the pair of directives, the cdkDropListDropped output and the moveItemInArray call with previousIndex and currentIndex. Say clearly that the CDK never touches your array.

for a middle

Explain why the row snaps back: the CDK restores the element's DOM position and only the array decides the order. Mention that moveItemInArray mutates in place, so a signal needs a copy.

for a senior

Show you have shipped it: stable @for tracking for duplicate tracks, skipping saves when the indexes match, and styling the placeholder and preview classes so users see where a track will land.

for a principal

Frame why the CDK reports intent instead of mutating state: it keeps one drag primitive usable with any data source, and puts persistence, validation and undo where the product logic already lives.

## The two directives and the event The Angular **Component Dev Kit (CDK)** ships drag and drop in `@angular/cdk/drag-drop`. It has no Material styling at all: it is a behaviour primitive that any component, Material or not, can use. Two directives do the everyday work: - **`cdkDrag`** goes on the element the user picks up. On its own, with no list around it, it makes the element *freely* draggable anywhere on the page. - **`cdkDropList`** goes on the parent element. It turns the `cdkDrag` children into a **sortable collection**: while one item is dragged, the others move aside, and a **placeholder** marks the slot where the item will land. When the user releases the item, the drop list emits **`cdkDropListDropped`**. Its payload is a **`CdkDragDrop`** event, and for a single list two of its fields matter: **`previousIndex`** (where the item was picked up) and **`currentIndex`** (where it was released). ## Why the CDK leaves your array alone The guide states it plainly: the drag-and-drop directives do not update your data model. That is a design choice, not a gap. The CDK does not know whether your rows come from a plain array, a signal, a store or a server page, and it cannot know whether a drop should be saved, rejected or undone. So it reports *what the user did* and leaves *what it means* to you. At the end of a drag the CDK also restores the dragged element to its original position in the DOM before emitting the event, so that Angular's own list rendering stays in charge of element order. The consequence is the classic beginner bug: a playlist with `cdkDropList` and `cdkDrag` but no `(cdkDropListDropped)` handler animates nicely during the drag, then the track **snaps back** to where it started, because the array that `@for` renders never changed. ## Writing the drop handler 1. Import `CdkDropList`, `CdkDrag`, the `CdkDragDrop` type and `moveItemInArray` from `@angular/cdk/drag-drop`, and add the two directives to the component's `imports`. 2. Bind `(cdkDropListDropped)="drop($event)"` on the list element. 3. In `drop`, call **`moveItemInArray(array, event.previousIndex, event.currentIndex)`**. 4. If the tracks live in a signal, copy the array first, move the item in the copy and `set` or `update` the signal with it. `moveItemInArray` **mutates the array in place and returns `void`**. It shifts every element between the two indexes by one slot (it does not swap two elements), and it clamps out-of-range indexes into the array's bounds instead of throwing. Because it mutates, handing it the array stored in a signal changes the contents without telling the signal; the copy in step 4 is what makes the change visible. Why reference identity matters to a signal is a general framework topic; here it is simply the reason for the copy. ## What the event carries | Field | Meaning | |---|---| | `previousIndex` | Index of the item when it was picked up | | `currentIndex` | Index where it was released | | `container` | The `CdkDropList` it was dropped into | | `previousContainer` | The `CdkDropList` it came from (the same list in a single-list sort) | | `item` | The `CdkDrag` instance that was moved | | `isPointerOverContainer` | Whether the pointer was over the list at release | | `distance`, `dropPoint`, `event` | Drag distance, pointer position and the native mouse or touch event | The container fields only matter once several lists are connected; for one playlist the two indexes are enough. ## Details worth knowing - The handler also runs when the user drops the track back on its own slot. Then `previousIndex` equals `currentIndex` and `moveItemInArray` returns early, but a handler that also saves the order should check the indexes to skip a pointless request. - Track rows by a stable id in `@for` (for example `track track.id`), so a playlist holding the same song twice still renders correctly after a move. - The CDK adds CSS classes you can style: `.cdk-drag-placeholder` for the landing slot, `.cdk-drag-preview` for the floating copy, and `.cdk-drag-animating` while the item settles; a CSS `transition` on `transform` animates the sorting. - The directives react to mouse and touch input. A keyboard way to reorder (for example move-up and move-down buttons that call `moveItemInArray`) is an accessibility design question for the screen, not something the drop list provides.

  • What happens if you put cdkDrag on an element that has no cdkDropList around it?
    It becomes freely draggable: the user can move it anywhere and the CDK keeps the offset as a CSS transform. There is no sorting, no placeholder and no drop-list event. You read the result from `cdkDragEnded`, whose event carries `distance` and `dropPoint`, and `cdkDragFreeDragPosition` sets or restores the position explicitly, for example after navigating back to the page.
  • Why does cdkDropListDropped fire when the user puts a track back on its own slot, and does that matter?
    The list emits the event whenever a drag that ended in it finishes, so `previousIndex` can equal `currentIndex`. `moveItemInArray` returns early in that case and the array is untouched. It matters only when the handler does more than move the item, such as saving the playlist order or creating a new array for a signal: check the indexes first to skip a wasted request or render.
  • How do you animate the other tracks sliding aside and the dropped track settling into place?
    Add a CSS `transition` on `transform`. A transition on `.cdk-drag` animates the rows as they are sorted, and one on `.cdk-drag-animating` animates the released item from the drop point to its final slot; that class is present only after the drag stops. Style `.cdk-drag-placeholder` to show the landing slot and `.cdk-drag-preview` for the copy that follows the pointer.

  • cdkDropList reorders the bound array automatically when the user drops an item.
  • moveItemInArray returns a new reordered array that you must assign back.
  • The track snaps back because cdkDropListData was not bound on the list.
  • cdkDrag alone makes a list sortable without any container directive.
  • Reorder the array in cdkDragMoved so the data follows the pointer live.