skip to content

In the Angular CDK drag-drop module, how do you connect a track library to a play queue so tracks can move between them?

level: middleimportance: must knowfreq 40%

answer

  1. lists are isolated by default
  2. a reference or an id
  3. connections have a direction
  4. a wrapper for many lists
  5. move within, transfer across

basics

~20 s

Connect the Angular CDK drop lists with cdkDropListConnectedTo, by reference or id, or wrap them in cdkDropListGroup. Bind each array with cdkDropListData, and in the drop handler call moveItemInArray for the same list or transferArrayItem across lists.

solid answer

~40 s

Drop lists in the Angular CDK are isolated until you connect them. `[cdkDropListConnectedTo]` takes other lists, either template references exported as `cdkDropList` or their `id` strings, and it is **directional**: it names where *this* list's items may go, so a two-way flow needs both lists to name each other. `cdkDropListGroup` on a shared ancestor connects every drop list inside it automatically, which suits a varying number of lists. Bind each list's array with `[cdkDropListData]` so one handler can work for all lists. The drop event fires on the list where the track lands; the handler checks `event.previousContainer === event.container` and calls `moveItemInArray` for a reorder or `transferArrayItem(previousContainer.data, container.data, previousIndex, currentIndex)` for a move between lists.

code

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

interface Track { id: string; title: string; }
type TrackList = WritableSignal<Track[]>;

@Component({
  selector: 'app-queue-editor',
  imports: [CdkDropListGroup, CdkDropList, CdkDrag],
  template: `
    <div cdkDropListGroup>
      @for (list of [library, queue]; track $index) {
        <ul cdkDropList [cdkDropListData]="list" (cdkDropListDropped)="drop($event)">
          @for (t of list(); track t.id) { <li cdkDrag>{{ t.title }}</li> }
        </ul>
      }
    </div>
  `,
})
export class QueueEditor {
  readonly library: TrackList = signal<Track[]>([{id: 'a', title: 'Blue Hour'}]);
  readonly queue: TrackList = signal<Track[]>([]);

  drop(e: CdkDragDrop<TrackList>) {
    const from = [...e.previousContainer.data()];
    const to = e.previousContainer === e.container ? from : [...e.container.data()];
    if (from === to) moveItemInArray(to, e.previousIndex, e.currentIndex);
    else transferArrayItem(from, to, e.previousIndex, e.currentIndex);
    e.previousContainer.data.set(from);
    e.container.data.set(to);
  }
}

go deeper

for a junior

Recall the two ways to connect lists, cdkDropListConnectedTo and cdkDropListGroup, and that crossing lists uses transferArrayItem instead of moveItemInArray.

for a middle

Explain the direction of a connection, that ids resolve at drag start, and why the handler belongs on every receiving list and compares previousContainer with container.

for a senior

Show production habits: cdkDropListData for one generic handler, copying both arrays when they live in signals, and the receiving class to highlight valid targets during a drag.

for a principal

Discuss the asymmetry as a product tool: one-way connections encode a workflow, such as library to queue only, without validation code, while a group trades that control for zero maintenance.

## Lists start isolated In the Angular CDK, a `cdkDropList` only sorts its own `cdkDrag` children. A track picked up in the library cannot enter the queue until the two lists are **connected**. The CDK offers two ways to connect them, and the drop handler then has to update *two* arrays instead of one. ## Connecting with cdkDropListConnectedTo **`cdkDropListConnectedTo`** is an input on `cdkDropList`. It accepts a single list or an array, and each entry is either: - a **direct reference** to another drop list, usually a template variable such as `#queueList="cdkDropList"` (the directive's `exportAs` name is `cdkDropList`), or - the **`id` string** of another drop list. Every list gets a generated id, and you can set your own with `id="queue"`. The connection is **one-way**. The CDK looks up candidate targets from the list where the drag *started*, so `[cdkDropListConnectedTo]="[queueList]"` on the library lets library tracks enter the queue, while tracks picked up in the queue can still only be sorted inside the queue. For a two-way flow, each list names the other. The asymmetry is useful: a library that feeds a queue but never receives from it needs only one connection. String ids are resolved when a drag starts, not when the template renders, so a list that appears later still connects. If no list has that id, the CDK prints a development-mode warning that it could not find the connected drop list, and the target simply never receives items. ## Connecting with cdkDropListGroup **`cdkDropListGroup`** is a directive for a common ancestor. Every `cdkDropList` inside it is connected to every other one, in both directions, and lists that `@for` adds later join automatically. It is the right tool when the number of lists varies, such as one list per user-created playlist. A group can be combined with `cdkDropListConnectedTo`: the explicit connections and the group's members are merged. `cdkDropListGroupDisabled` switches the whole group off. | Need | Use | |---|---| | Two or three fixed lists, possibly one-way | `cdkDropListConnectedTo` on each source list | | A dynamic number of lists, all mutually connected | `cdkDropListGroup` on a shared ancestor | | A one-way flow among many lists | Explicit `cdkDropListConnectedTo`, or a group plus enter predicates | ## Writing one handler for every list 1. Bind each list's array with **`[cdkDropListData]`**. The data is optional for dragging, but it lets a handler find the arrays through `event.previousContainer.data` and `event.container.data` instead of hard-coding them. 2. Bind `(cdkDropListDropped)` on **every list that can receive** items. The event is emitted by the list where the item is dropped, so a handler only on the library never sees a track dropped into the queue. 3. In the handler, compare **`event.previousContainer === event.container`**. 4. Same list: `moveItemInArray(event.container.data, event.previousIndex, event.currentIndex)`. 5. Different lists: **`transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex)`**. It removes the item from the source array and inserts it into the target at the new index. Both helpers **mutate** the arrays you pass. When the arrays live in signals, copy both, transfer between the copies and set both signals, otherwise the signals never see the change. ## A worked flow: library to queue only Suppose the library should feed the queue, queue tracks must never go back to the library, and the queue may be reordered freely. - Put `[cdkDropListConnectedTo]="[queueList]"` on the library and nothing on the queue. Library tracks can enter the queue; queue tracks can only be sorted inside the queue. - Bind `(cdkDropListDropped)` on the queue. A library track dropped there arrives with `previousContainer` set to the library and `container` set to the queue, so the handler takes the transfer branch. - Bind the handler on the library too if users may reorder the library itself, because a drag that starts and ends in the library emits on the library. - If the library must keep the track (a copy rather than a move), the same connection works and only the handler changes. Nothing in this flow needs validation code: the direction of the connection *is* the rule. ## What a candidate should also mention - While a drag is in progress, the CDK adds **`.cdk-drop-list-receiving`** to each list that can take the item, and **`.cdk-drop-list-dragging`** to the list that currently holds it, so you can highlight valid targets. - Moving is not copying. `transferArrayItem` takes the track out of the library; if the library should keep it, that is a copy flow built with `copyArrayItem` and usually an anchor in the source list. - Connecting lists says *where* items may go; which items a list accepts is a separate decision made with an enter predicate. - `cdkDropListDisabled` on one list, or `cdkDragDisabled` on one track, stops dragging without removing the connection.

  • The queue names the library with cdkDropListConnectedTo="library", yet library tracks cannot be dropped into the queue. Why?
    The connection points the other way. `cdkDropListConnectedTo` on the queue lets queue tracks move into the library; candidate targets are looked up from the list where the drag starts. Add `cdkDropListConnectedTo` naming the queue on the library list. Also confirm the library really has `id="library"`: an unknown id only produces a development-mode console warning.
  • When do you prefer cdkDropListGroup over cdkDropListConnectedTo?
    Use the group when the number of lists varies, such as one list per saved playlist rendered by `@for`: every list inside it connects to every other one, both ways, with nothing to maintain. Use `cdkDropListConnectedTo` for a small fixed set or a deliberately one-way flow, such as a library that feeds a queue. The two combine; a list's explicit connections and its group members are merged.
  • Why bind cdkDropListData if dragging works without it?
    Because the drop event then carries the arrays. `event.previousContainer.data` and `event.container.data` give the source and target arrays, so one generic handler serves any number of lists and passes them straight to `moveItemInArray` or `transferArrayItem`. Without it, the handler has to work out which array belongs to which list, which breaks as soon as lists are added dynamically.

  • cdkDropListConnectedTo links both lists, so only one side needs the input.
  • transferArrayItem copies the track and leaves it in the source list.
  • The drop event fires on the source list, so only that list needs a handler.
  • Lists inside cdkDropListGroup need matching ids before they connect.
  • Connected lists refuse items unless cdkDropListData is bound on both.