skip to content

In an Angular CDK playlist editor, how do cdkDropListEnterPredicate and cdkDropListSortPredicate keep explicit tracks out of a kids queue and pin the opening track?

level: seniorimportance: should knowfreq 26%

answer

  1. decide during the drag, not after
  2. one gate per list, one per index
  3. read the item through cdkDragData
  4. arrow function, not a method
  5. the origin list always takes it back

basics

~20 s

In the Angular CDK, cdkDropListEnterPredicate(drag, drop) decides whether a list accepts an incoming item, and cdkDropListSortPredicate(index, drag, drop) decides whether an item may move to an index. Both return booleans, run during the drag and read the item through cdkDragData.

solid answer

~50 s

Both are inputs on `cdkDropList` that take functions and default to allowing everything. The **enter predicate** receives the `CdkDrag` and the `CdkDropList` and runs as an item is dragged towards a connected list; returning `false` keeps the list from receiving it, so `drag.data.explicit` (with `[cdkDragData]="track"`) can keep explicit tracks out of the kids queue. The **sort predicate** receives the candidate index, the drag and the list each time an item is about to move to a new index; `index !== 0` stops anything taking the opening slot, and `cdkDragDisabled` on the pinned row stops it leaving. Two traps: the directive invokes your function as its own property, so a class method that reads `this` loses the component, which is why arrow-function properties are used; and predicates run many times per drag, so they must be cheap and synchronous.

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; explicit: boolean; pinned: boolean; }

@Component({
  selector: 'app-kids-queue',
  imports: [CdkDropList, CdkDrag],
  template: `
    <ol cdkDropList id="kids-queue"
        [cdkDropListEnterPredicate]="kidsSafe"
        [cdkDropListSortPredicate]="notFirstSlot"
        (cdkDropListDropped)="drop($event)">
      @for (t of queue(); track t.id) {
        <li cdkDrag [cdkDragData]="t" [cdkDragDisabled]="t.pinned">{{ t.title }}</li>
      }
    </ol>
  `,
})
export class KidsQueue {
  readonly queue = signal<Track[]>([]);
  readonly parentalLock = signal(true);

  readonly kidsSafe = (drag: CdkDrag<Track>) => !(this.parentalLock() && drag.data.explicit);
  readonly notFirstSlot = (index: number) => index !== 0;

  drop(e: CdkDragDrop<Track[]>) {
    // same-list reorder shown; a cross-list drop would use transferArrayItem
    this.queue.update(q => { const n = [...q]; moveItemInArray(n, e.previousIndex, e.currentIndex); return n; });
  }
}

go deeper

for a junior

Recall that cdkDropListEnterPredicate decides whether a list accepts an item and cdkDropListSortPredicate decides allowed positions, and that both return true or false.

for a middle

Explain the signatures, reading the item through cdkDragData and drag.data, and why pinning needs cdkDragDisabled as well as a sort predicate that refuses index 0.

for a senior

Show the production traps: the this binding that breaks class methods, predicates running on every pointer move, the origin-list exception, and server validation behind the UI gate.

for a principal

Discuss where rules belong: predicates give instant feedback but duplicate business rules in the client, so derive them from the same policy data the server enforces.

## Two gates that run during the drag Connecting lists in the Angular CDK says *where* items may go. Two inputs on `cdkDropList` decide *which* items and *which positions* are allowed, while the user is still dragging, so a forbidden drop never happens and no drop handler has to undo it. | Input | Signature | Called when | `false` means | |---|---|---|---| | `cdkDropListEnterPredicate` | `(drag: CdkDrag, drop: CdkDropList) => boolean` | An item is dragged towards this list from a connected list | The list does not receive the item | | `cdkDropListSortPredicate` | `(index: number, drag: CdkDrag, drop: CdkDropList) => boolean` | An item is about to move to a new index in this list | The item stays at its current position | Both default to a function that returns `true`. ## Keeping explicit tracks out of the kids queue The predicate gets the `CdkDrag` instance, not your track object. To reach the track, bind **`[cdkDragData]="track"`** on each row and read **`drag.data`** inside the predicate. The list's own data is available as `drop.data` when it is bound with `cdkDropListData`. ```ts readonly kidsSafe = (drag: CdkDrag<Track>) => !drag.data.explicit; ``` The CDK evaluates the enter predicate when a drag starts, to decide which connected lists begin **receiving** (those lists get the `.cdk-drop-list-receiving` class, a cheap way to highlight valid targets), and again whenever the pointer is over a candidate list. An explicit track simply never enters the kids queue; the user sees it refuse. One exception is built in: an item can always return to the list it **started in**, even if that list's own enter predicate returns `false`. That is what lets a palette or library use `() => false` to refuse items from *other* lists while its own items can still be dragged back home. ## Pinning the opening track The sort predicate controls positions within a list: 1. Mark the opening track's row with **`[cdkDragDisabled]="track.pinned"`** so nobody can pick it up. 2. Set **`[cdkDropListSortPredicate]="notFirstSlot"`** with `notFirstSlot = (index: number) => index !== 0`, so no other track can be sorted into index 0. The predicate alone is not enough: the pinned track could still be dragged away from index 0, letting the next track slide into the slot. Each gate covers one direction. When an item would move to a refused index, the CDK leaves it where it is, so the placeholder simply stops at index 1. If a list must not be sorted at all, for example a read-only library that only feeds the queue, **`cdkDropListSortingDisabled`** is simpler than a predicate that always returns `false`. `cdkDropListDisabled` turns the whole list off. ## Choosing the right gate | Requirement | Tool | |---|---| | Keep a category of items out of a list | `cdkDropListEnterPredicate` | | Forbid certain positions inside a list | `cdkDropListSortPredicate` | | Freeze a list's own order entirely | `cdkDropListSortingDisabled` | | Stop one item being picked up | `cdkDragDisabled` | | Stop a whole list taking part | `cdkDropListDisabled` | | Limit which lists an item can reach at all | The direction of `cdkDropListConnectedTo` | Prefer the most structural tool that expresses the rule. A connection or a disabled flag cannot suffer from a `this` bug and costs nothing per pointer move; a predicate is for rules that depend on the item's data or on changing state, such as a parental-lock toggle. ## The traps - **`this` inside a method.** The directive stores your function and calls it as its own property (`this.enterPredicate(drag.data, drop.data)` inside `CdkDropList`). A class *method* passed as `[cdkDropListEnterPredicate]="isAllowed"` therefore runs with `this` set to the drop list directive, and `this.parentalLock` is `undefined`. Use an **arrow-function property**, or a function that reads nothing from `this`. - **Frequency.** Predicates run on many pointer moves during one drag. Keep them pure, synchronous and cheap: no HTTP calls, no heavy computation, no state changes. Precompute what you need, such as a set of blocked genres, before the drag. - **Not a security check.** A predicate shapes the interaction; the server that stores the queue still validates what it receives. - **Feedback.** A refused list gives no message by itself. Use the receiving class, or `cdkDragEntered` and `cdkDragExited`, to explain why a track will not go in.

  • Your enter predicate is a class method that reads this.parentalLock, and it throws 'cannot read properties of undefined'. Why?
    `CdkDropList` stores the function in its `enterPredicate` property and calls it as `this.enterPredicate(...)`, so inside your method `this` is the drop list directive, not your component, and it has no `parentalLock`. Declare the predicate as an arrow-function property, which captures the component, or bind it once in the constructor.
  • A library list uses cdkDropListEnterPredicate returning false. Can a user still drag a library track out and back again?
    Yes. The CDK makes an exception for the list where a drag started: an item can always return to its origin, even when that list's enter predicate refuses. The predicate only keeps out items picked up in other lists, which is exactly what a library or palette that must not receive anything needs.
  • Would you validate the kids queue in the drop handler as well?
    Not for the interaction: a refused list never receives the item, so the kids queue's drop handler never fires for it. Validate on the server that saves the queue, since a predicate is client-side behaviour that other clients or scripts bypass. In the client, also make sure the predicate and the server rule come from the same data, so they cannot drift.

  • The enter predicate runs once, on drop, after the item lands in the list.
  • The predicate receives the track object directly, so cdkDragData is unnecessary.
  • Passing a class method as the predicate keeps this bound to the component.
  • A sort predicate rejecting index 0 is enough to pin the opening track there.
  • A list whose enter predicate returns false can never take back its own items.