Utilities
Drag & Drop
Headless, accessible drag-and-drop for sortable lists and cross-list transfers, driven by both keyboard and pointer. Ships drag handles, custom preview / placeholder templates, live-sort, FLIP reorder animations, auto-scroll, and boundary / axis-lock constraints.
Drag a row with the pointer, or lift it with Space and move it with the arrow keys. During the drag, data-dragging is on the item and data-drag-over on the list it is over.
- Draft the release notes
- Review open pull requests
- Update the changelog
- Publish the npm package
- Announce on the forum
For repositioning an arbitrary element (no list, no reorder), such as dragging a
whole dialog around by its header, see [forFreeDrag].
Anatomy
<div forDropListGroup>
<ul forDropList (dragDrop)="onDrop($event)">
@for (item of items(); track item.id) {
<li forDraggable [dragData]="item">
<span forDragHandle>⠿</span>
{{ item.label }}
<ng-template forDragPreview>…floating preview…</ng-template>
<ng-template forDragPlaceholder>…gap left behind…</ng-template>
</li>
}
</ul>
<!-- repeat forDropList per connected list -->
</div>
| Piece | Selector | Required | Role | |
|---|---|---|---|---|
| Drop list | [forDropList] | yes | Owns the sortable container: registers its items, computes the drop index, emits (dragDrop), and hosts auto-scroll and the live announcements. | |
| Draggable item | [forDraggable] | yes | One per item. Carries the item's [dragData], the keyboard lift, and the data-dragging / data-disabled hooks. | |
| Drag handle | [forDragHandle] | no | Restricts the pointer grab to one child. Without it the whole item is the handle. | |
| Preview template | [forDragPreview] | no | On an <ng-template> inside the item: replaces the default clone that follows the pointer. Pointer drags only. | |
| Placeholder template | [forDragPlaceholder] | no | On an <ng-template> inside the item: replaces the default gap held open in the dragged item's slot. Pointer drags only. | |
| Drop-list group | [forDropListGroup] | only for transfers | Connects sibling lists so items move between them. [connectedTo] on each list is the alternative when the lists are not siblings. | |
| Free drag | [forFreeDrag] | standalone | Not part of this anatomy: free repositioning with no list and no reorder. See Free drag. |
onDrop applies moveItemInArray (or transferArrayItem) to your own signal: the primitive never
mutates the consumer's data, in either the pointer or the keyboard flow.
Examples
Drag follows scroll (auto-scroll)
When a pointer drag reaches the edge of a scrollable container that can still scroll that way (the list, a scrollable ancestor, or the page), [forDropList] auto-scrolls it toward that edge so you can drop on items far outside the visible window. The edge zone and max speed are tuned via provideForDragDropDefaults. Keyboard dragging is unaffected.
- 1Aphex Twin — Track 01
- 2Boards of Canada — Track 02
- 3Bonobo — Track 03
- 4Four Tet — Track 04
- 5Jon Hopkins — Track 05
- 6Floating Points — Track 06
- 7Aphex Twin — Track 07
- 8Boards of Canada — Track 08
- 9Bonobo — Track 09
- 10Four Tet — Track 10
- 11Jon Hopkins — Track 11
- 12Floating Points — Track 12
- 13Aphex Twin — Track 13
- 14Boards of Canada — Track 14
- 15Bonobo — Track 15
- 16Four Tet — Track 16
- 17Jon Hopkins — Track 17
- 18Floating Points — Track 18
- 19Aphex Twin — Track 19
- 20Boards of Canada — Track 20
- 21Bonobo — Track 21
- 22Four Tet — Track 22
- 23Jon Hopkins — Track 23
- 24Floating Points — Track 24
- 25Aphex Twin — Track 25
- 26Boards of Canada — Track 26
- 27Bonobo — Track 27
- 28Four Tet — Track 28
- 29Jon Hopkins — Track 29
- 30Floating Points — Track 30
Transfer between lists
Wrap two [forDropList] columns in [forDropListGroup] and they connect automatically. The (dragDrop) event fires on the source list with previousContainer / container contexts; compare them to choose moveItemInArray (same list) or transferArrayItem (across lists).
To do · 3
- Sketch the wireframes
- Wire up the API
- Write the tests
Done · 2
- Set up the repo
- Pick the colour palette
Axis lock, boundary & custom preview
A horizontal palette where lockAxis='x' pins the preview to its lift-time vertical position and [boundary] clamps it inside the dashed frame. A custom [forDragPreview] template replaces the default clone, and [forDragPlaceholder] fills the source slot. Both constraints affect only the pointer preview, never the resolved drop index.
- Teal
- Coral
- Indigo
- Amber
- Rose
Wrapping grid (mixed orientation)
Drag a tile across the wrap into the row below: with orientation='mixed' the placeholder follows the pointer's row and column, where a single-axis list would snap to the nearest slot along one line. Orientation compares the three modes and the scope-wide default.
- A
- B
- C
- D
- E
- F
- G
- H
Free drag (forFreeDrag)
Drag the card anywhere inside the dashed box, its boundary, which it cannot leave. The panel moves by the grip in its header: rootElement makes that handle move the whole panel. Both are pointer-only; Free drag says why, and lists the inputs and outputs.
API
There is no single table of every input here: each piece is introduced with the flow that uses it (the sortable-list surface under Pointer dragging, the standalone one under Free drag), because listing nine directives in one place would introduce every one of them out of context. What every flow shares is the attribute surface below.
Data attributes
| Attribute | Element | Meaning | |
|---|---|---|---|
data-orientation | [forDropList] | "vertical", "horizontal", or "mixed" | |
data-disabled | both | Present when the item or list is disabled | |
data-disabled | [forFreeDrag] | Present when the free-drag element is disabled | |
data-dragging | [forDropList] | Present while a drag originates here | |
data-dragging | [forDraggable] | Present while this item is lifted | |
data-dragging | [forFreeDrag] | Present while a free-drag pointer gesture is armed | |
data-drag-over | [forDropList] | Present while this list is the drop target | |
data-drag-handle | [forDragHandle] | Present on every registered drag handle | |
data-for-drag-preview | preview element | Present on the default clone preview or the [forDragPreview] template wrapper | |
data-drag-animating | [forDraggable] | Present while the item's FLIP reorder transition plays (requires [animateReorder]) | |
data-settling | preview element | Present while the drop-settle transition plays (requires [animateReorder]) |
Both data-dragging rows hold for a drag a coordinator composing the list owns rather
than starting through [forDraggable] itself: the keyboard lift of [forVirtualReorder], and
the virtualized branch of [forTableRowReorder]. Those intercept the lift key before the item
sees it, so the list carries no lift state for the gesture, and the coordinator marks the item
instead. Styling keyed off either attribute therefore behaves the same whether the collection is
windowed or not, and the item's (dragStart) / (dragEnd) fire for those gestures too.
The data-for-drag-preview row is also the supported hook for keeping the clone out of element
queries. The default preview is a cloneNode(true) copy appended to document.body, so for the
whole gesture (and past the drop, while a settle transition runs) it answers the item's own
selector ([forDraggable], or a composed one such as [forTableRow]) and repeats its data-index.
id and data-testid are stripped from the clone and its whole subtree, so a hook that identifies
a single element stays unambiguous; anything that enumerates items by attribute selector during
a drag must filter the preview out with :not([data-for-drag-preview]). The clone is also made
inert before it joins the document: name, form, autofocus and autoplay are stripped, and
every iframe, object and embed becomes an empty box of the same size, so a cloned radio never
unchecks the item's own and no cloned media plays or frame reloads.
Keyboard
| State | Key | Action | |
|---|---|---|---|
| Idle | Arrow keys | Move roving focus between items | |
| Idle | Home / End | Jump to first / last item | |
| Idle | Space/Enter | Lift the focused item | |
| Lifted | Arrow keys | Step the logical drop position, across connected lists | |
| Lifted | Home / End | Jump the lifted item to the first / last position | |
| Lifted | Space/Enter | Drop (commits, emits (dragDrop), focus follows the item) | |
| Lifted | Escape | Cancel (no event, focus stays on item) |
Removing the focused item outside a drop moves focus to the item that takes over the Tab stop, the one
before it or else the one after, so focus never falls to <body>. A drop keeps the rules of
Focus after a keyboard drop.
Arrow direction follows the list's orientation and respects RTL via dir. In
orientation="mixed" every arrow key steps the lifted item linearly in DOM order.
With connected lists ([forDropListGroup] or [connectedTo]), the lifted item steps through one
sequence of positions: every position of the list it was lifted from, then every position of each
connected list, including the append position past its last item. Connected lists come in
[connectedTo] order, then in the order the group's lists registered. Home and End jump to the two
ends of that sequence, and a step past either end does nothing and announces nothing. The
announcement names the list a position belongs to whenever it is not the source list, so a
transfer never sounds like a reorder.
[dragDisabled] and a disabled [forDropList] stop a lift from starting, nothing else. A
[dragDisabled] item still takes the idle arrow and Home / End keys (only a disabled list stops
those), and an item that was already lifted when it or its list became disabled keeps every lifted
key, so Escape always ends the gesture.
Accessibility
Keyboard lifting, stepping, dropping, and cancellation are announced via ARIA live regions. Override the default messages at any injector scope via provideForDragDropDefaults (see Scoped defaults). Free-drag is pointer-only. There is no WAI-ARIA pattern for "reposition an element", so [forFreeDrag] owns no role or ARIA state; the consumer is responsible for keeping the moved element fully usable at its default position.
Item names
Every lift, move, drop and cancel announcement names the item the way a screen reader would: by
the text its aria-labelledby references, else by its aria-label, else by its text with any
aria-hidden content (such as a [forDragHandle] glyph) left out and a space between adjacent
elements. Set [textValue] on [forDraggable] to name an item in announcements by a string of
your own; an empty or null value falls back to the item's own name. The same name is used by
[forVirtualReorder] and [forTableRowReorder].
<li forDraggable [dragData]="task" [textValue]="task.title">
<strong>{{ task.title }}</strong><span>{{ task.due }}</span>
</li>
A list is named in an announcement by its aria-labelledby or aria-label, never by its items, so
label each list of a transfer.
Role description
Each [forDraggable] that can be lifted carries aria-roledescription, "sortable" by default.
An item that cannot be lifted, through [dragDisabled] or a disabled [forDropList], emits none.
A screen reader that honors the attribute speaks it in place of the element's role name, so
change it, or turn it off with an empty string, through itemRoleDescription at any injector
scope:
providers: [provideForDragDropDefaults({ itemRoleDescription: 'movable item' })];
The host needs a role that supports the attribute. ARIA 1.2 prohibits aria-roledescription on
the generic role, which is what a bare <div> or <span> and a <section> with no accessible
name have, so on one of those a screen reader drops the description and the item is announced with
no role at all. Put [forDraggable] on an <li> inside the <ul> or <ol> that carries
[forDropList], or give the item role="listitem" and its list role="list" when the markup has
to stay a <div>, as the rows of a virtualized list do.
[forTableColumnReorder] turns it off for its header cells, which keep the columnheader role
name and leave "sortable" to aria-sort.
Focus after a keyboard drop
Applying the move in (dragDrop) destroys or re-inserts the lifted element, which would otherwise
leave focus on <body>. So after a keyboard drop whose lifted item held focus, [forDropList]
restores focus on the next render to the item whose [dragData] is the dropped item, falling back to the
item at currentIndex in the target container when no item carries it any more. That is the item the user
just placed, whether it stayed in this list or transferred to a connected one, and whether the @for
tracks by item identity or by $index.
Two escape hatches:
- Focus something yourself inside the
(dragDrop)handler (a status region, a toolbar, the next row). The restore only fires when focus has already fallen to<body>, so whatever you focus wins. - Pointer drops are untouched: focus is never moved after a mouse / touch / pen drop.
If your handler leaves the data unchanged, nothing is detached and focus simply stays on the item.
Pointer dragging
When a pointer drag starts, the dragged item stays in place and reflects
data-dragging (style it as a dimmed gap). A fixed-position clone of the item
follows the pointer as the default preview. The clone carries
data-for-drag-preview and aria-hidden="true".
Auto-scroll
While a pointer drag is in flight, [forDropList] automatically scrolls toward
whichever edge the pointer approaches. The candidates are the list under the
pointer, then each scrollable ancestor, then the viewport, and the first one whose
edge the pointer is near and that can still scroll that way is the one that
scrolls. So a fully scrolled list hands the edge to the panel around it, and a
panel whose bottom edge is below the fold hands it to the page. Both axes are
covered, and under dir="rtl" the left edge scrolls toward the inline end. Speed
scales with proximity: the closer the pointer is to the edge, the faster the
scroll.
The feature is on by default. Opt out with [autoScroll]="false":
<ul forDropList [autoScroll]="false" (dragDrop)="onDrop($event)">
…
</ul>
Configure the edge zone and max speed via provideForDragDropDefaults:
providers: [
provideForDragDropDefaults({
autoScrollEdgeSize: 80,
autoScrollMaxSpeed: 24,
}),
];
Keyboard dragging is unaffected. Auto-scroll is SSR-safe: it is a no-op when there is no browser window.
Optional drag handle
Apply [forDragHandle] on a child element of [forDraggable] to restrict
where a pointer gesture may start. Once any handle is present on an item,
pointer drags may only begin from within that handle. Keyboard dragging is
unaffected.
<li forDraggable [dragData]="item">
<span forDragHandle aria-hidden="true">::</span>
{{ item.label }}
</li>
A handle carries touch-action: none, so a touch drag on it is not taken by the page's
scrolling, and the item around it leaves touch scrolling alone. Both follow the item: a handle
mounted or removed after the first render moves the touch-action: none between the handle and
the item, and a disabled item or list drops it from both.
An item with no handle carries touch-action: none itself, so it takes every touch move that
starts on it. A scroller made only of handle-less items, such as a virtualized list or an
overflow: auto kanban column, therefore cannot be scrolled by touch. Give those items a
[forDragHandle]: the rest of each item then pans the scroller, and the handle starts the drag.
Native drag
Images, links and selected text are draggable by the browser itself, and its own drag starts
before a pointer drag arms. A [forDraggable] or [forFreeDrag] therefore cancels the native
dragstart of every press it would turn into a pointer drag, so pressing a thumbnail inside an
item reorders the item instead of dragging a copy of the image. Content outside the item's
handles, and every press while the item or its list is disabled, keeps its native drag. The
same holds for every pointer reorder in the library: [forTreeNodeDrag], [forListboxReorder],
table row reorder and [forVirtualReorder].
Nested controls
A control inside a draggable item keeps its press from starting a drag by calling
preventDefault() on its own pointerdown. The item stands down on the first pointer move, so
the press stays with the control; lifting with the keyboard is unaffected.
<li forDraggable [dragData]="item">
{{ item.label }}
<button type="button" (pointerdown)="$event.preventDefault()" (click)="remove(item)">
Remove
</button>
</li>
- The check lives in the pointer session every drag surface shares, so it holds for
[forDraggable],[forFreeDrag],[forListboxReorder],[forTableRowReorder],[forTreeNodeDrag]and[forVirtualReorder]alike. - A nested control that runs a drag of its own still starts it: the item around it is what
stands down. That is how a
[forTableColumnResizer]resizes inside a reorderable header cell. - A canceled
pointerdownsuppresses the compatibility mouse events of that press (mousedown,mouseup), so the control must not rely on them.clickstill fires.
A [forDraggable] or [forFreeDrag] nested inside another one needs no preventDefault(): every
press inside it is its own, and the item around it never starts a drag from there, even while the
nested one is disabled. On a board whose columns are the items of one list and hold a list of
cards each, pressing a card drags the card, and pressing a column outside its cards drags the
column. Each item lifts with its own [forDragPreview] / [forDragPlaceholder], never with one
declared inside a nested item.
<ul forDropList orientation="horizontal" (dragDrop)="moveColumn($event)">
@for (column of columns(); track column.id) {
<li forDraggable [dragData]="column">
<h2>{{ column.title }}</h2>
<ul forDropList (dragDrop)="moveCard(column, $event)">
@for (card of column.cards; track card.id) {
<li forDraggable [dragData]="card">{{ card.title }}</li>
}
</ul>
</li>
}
</ul>
Custom preview & placeholder
Place <ng-template forDragPreview> and/or <ng-template forDragPlaceholder> as direct
children of [forDraggable] to override the default drag visuals during a pointer drag.
<li forDraggable [dragData]="item">
{{ item.label }}
<ng-template forDragPreview>
<div class="my-preview">{{ item.label }}</div>
</ng-template>
<ng-template forDragPlaceholder>
<div class="my-placeholder"></div>
</ng-template>
</li>
[forDragPreview]replaces the default cloned floating element that follows the pointer during a pointer drag. Applies to pointer drags only; keyboard dragging is unaffected.[forDragPlaceholder]renders in the dragged item's slot while a pointer drag is in flight. The dragged item's host is hidden (display: none) and the placeholder template occupies its space, preserving the gap. When the drag ends (drop or cancel) the placeholder is removed and the item is revealed again. Keyboard dragging keeps the default behaviour: the lifted item stays in place reflectingdata-dragging, and no placeholder is rendered.
Live-sort placeholder
Add [liveSort]="true" to [forDropList] to make the [forDragPlaceholder] follow the live
resolved drop index during a pointer drag (within the list and across connected lists), so
siblings part to reveal where the item will land. When false (the default), the placeholder
stays in the dragged item's source slot.
<ul forDropList [liveSort]="true" (dragDrop)="onDrop($event)">
@for (item of items(); track item.id) {
<li forDraggable [dragData]="item">
{{ item.label }}
<ng-template forDragPlaceholder>
<div class="my-placeholder"></div>
</ng-template>
</li>
}
</ul>
[liveSort] has no visible effect without a [forDragPlaceholder] template, and has no effect
on keyboard dragging. The drop index is resolved from the geometry measured at lift, so
[liveSort] never changes which index a pointer path commits. It only moves the placeholder.
Boundary & axis lock
[forDropList] supports two opt-in visual constraints on the pointer-drag preview. Both are
null by default and have no effect on keyboard dragging (which has no floating preview).
They constrain the visual preview only and never change the resolved drop index.
[boundary]: confine the preview within a boundary element. Accepts an HTMLElement or
a CSS selector string resolved via closest() from the list host. The preview box is clamped so
it stays fully inside the boundary. When the boundary is smaller than the preview on an axis,
the preview is pinned to the boundary's start edge on that axis.
[lockAxis]: constrain movement to one axis. 'x' keeps the preview at its lift-time y
(horizontal-only movement); 'y' keeps it at its lift-time x (vertical-only movement).
Both inputs may be combined:
<div class="container" #container>
<ul forDropList [boundary]="container" lockAxis="x" (dragDrop)="onDrop($event)">
@for (item of items(); track item.id) {
<li forDraggable [dragData]="item">{{ item.label }}</li>
}
</ul>
</div>
String selector form (resolved via closest() on the list host):
<ul forDropList [boundary]="'.my-scroller'" (dragDrop)="onDrop($event)">
…
</ul>
Reorder & settle animations
Add [animateReorder]="true" to [forDropList] to animate committed drops. When enabled:
- FLIP reorder: displaced sibling items transition smoothly from their old positions to their new ones instead of snapping.
- Drop-settle: on a pointer drag, the floating preview transitions from its release position into the final item slot before it is removed.
Both are opt-in and fully skipped under prefers-reduced-motion: reduce. They work for both
keyboard and pointer drags. The library publishes the styling hooks below. Duration / easing are
always provided by the consumer via CSS; the library imposes none.
<ul forDropList [animateReorder]="true" (dragDrop)="onDrop($event)">
…
</ul>
[forDraggable][data-drag-animating] {
transition: transform 200ms ease;
}
[data-for-drag-preview][data-settling] {
transition: transform 200ms ease;
}
With no such CSS, animateReorder is a graceful no-op: data-drag-animating clears instantly
and the preview is destroyed promptly. Otherwise a displaced item keeps data-drag-animating, and
the preview stays mounted, until its own transform transition ends, and never before that
transition's transition-delay plus duration have elapsed, wherever transform sits in a
multi-property transition list. A transition of another property, or one running on a
descendant, ends neither.
Orientation
[forDropList] resolves the live drop index along its orientation:
"vertical"(default): a stacked column; the index is resolved by the pointer'sy."horizontal": a single row; the index is resolved by the pointer'sx(RTL-aware)."mixed": a wrapping grid (flex-wrap/ CSS grid) of uniformly-sized items. The index is resolved in 2D, so an item dragged across a wrapped row lands in the slot under the pointer's row and column instead of mis-resolving to the nearest single-axis slot. A"mixed"list that happens to render as a single row or single column resolves identically to"horizontal"/"vertical".
In a cross-list transfer each container resolves the drop index on its own orientation and
dir, so a vertical list can be connected to a horizontal one (or to one in the opposite writing
direction) and the pointer index lands on the target's axis.
<ul class="grid" forDropList orientation="mixed" (dragDrop)="onDrop($event)">
@for (item of items(); track item.id) {
<li forDraggable [dragData]="item">{{ item.label }}</li>
}
</ul>
.grid {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
A wrapper can default the orientation for every [forDropList] in its scope via the
FOR_DROP_LIST_DEFAULT_ORIENTATION token (the same mechanism ForTableColumnReorder uses for
"horizontal"):
providers: [{ provide: FOR_DROP_LIST_DEFAULT_ORIENTATION, useValue: 'mixed' }];
"mixed" targets regular grids of uniformly-sized items; variable-size / masonry layouts are out of
scope. [animateReorder] (FLIP) reflows by DOM order and needs no change in mixed mode.
Free drag
[forFreeDrag] repositions its host element (or a resolved rootElement) by pointer drag, with
no [forDropList] required. It never commits a reorder; it just moves the element around via
the CSS translate property. It is the standalone counterpart to a sortable list item: a
pointer-driven way to move an element freely, with optional root-element retargeting, a confinement
boundary, axis locking, and a controllable position (see the inputs below).
The offset composes with the transform and the translate the moved element already has, inline
or from a stylesheet, so a dialog centred with transform: translate(-50%, -50%) or
translate: -50% -50% stays centred and moves from there. The translate it composes with is read
when the element first leaves its rest position, and the element's own translate comes back once
position returns to { x: 0, y: 0 }.
Scrolling the page or a scroll container during a drag keeps the element under the pointer, and the
boundary clamp follows the scrolled geometry.
<!-- move the whole dialog by its header -->
<div class="dialog">
<header forFreeDrag rootElement=".dialog" boundary=".viewport">Drag me</header>
…
</div>
<!-- or with an explicit handle and a controllable position -->
<div forFreeDrag [(position)]="pos" boundary=".viewport">
<span forDragHandle aria-hidden="true">⠿</span>
…
</div>
| Input | Type | Default | Meaning |
|---|---|---|---|
disabled | boolean | false | When true, the element can't be dragged (it stays focusable; its position doesn't change). |
rootElement | HTMLElement | string | null | null | The element actually moved. A closest() selector resolves an ancestor. null moves the host. |
boundary | HTMLElement | string | null | null | Confine the moved element fully inside this element (or closest() selector). null = unbounded. |
lockAxis | 'x' | 'y' | null | null | Constrain movement to one axis. 'x' pins lift-time y, 'y' pins lift-time x. |
position | model | { x:0,y:0 } | Two-way translate offset (px) from the element's natural position. Controllable / restorable. |
| Output | Payload | Fires | |
|---|---|---|---|
moveStart | { x; y } | When a pointer drag starts (the lift-time position). | |
moveMove | { x; y } | On every armed move, and when a scroll moves the element, with the live position. | |
moveEnd | { x; y } | When the drag ends (commit keeps the position; cancel/Escape restores the lift-time snapshot). |
[forDragHandle] works inside [forFreeDrag] exactly as it does inside [forDraggable]: once any
handle is present, a pointer drag may only start from within a handle.
Accessibility. Free-drag is pointer-only. There is no WAI-ARIA pattern for "reposition an element", so it owns no role or ARIA state. The consumer is responsible for keeping the moved element fully usable at its default position (e.g. a repositionable dialog must still be operable by keyboard); dragging is a pointer convenience, not the only way to use it.
Virtualized lists
Dragging the rows of a virtualized list (one whose off-screen rows are recycled out of the DOM) is supported through two opt-in companions:
- for a table,
[forTableRowReorder]composed with[forTableVirtualized], and - for a plain
*forVirtualForlist,[forVirtualReorder]composed with[forVirtualViewport](seeforty-cdk/virtual-reorder).
A bare [forDropList] wrapping *forVirtualFor is not supported on its own:
it only ever registers the rows currently rendered in the window, so it
- emits window-relative
previousIndex/currentIndex(applyingmoveItemInArrayover your full array reorders the wrong rows), - lets the lifted row get recycled out from under the drag when auto-scroll moves the window, and
- confines keyboard stepping to the rendered window, so it can't traverse the dataset.
Both companions solve all three: they translate window-relative to absolute
dataset indices (so moveItemInArray over the full array moves the right item),
pin the lifted row so auto-scroll never recycles it mid-drag, and step the
keyboard target over the true total count. Holding Shift during a pointer drag
additionally engages windowed scrub: the scroll viewport maps onto the whole
dataset (top edge → first item, bottom edge → last), so one gesture drops the
lifted row at an arbitrary far item without auto-scroll having to reach it.
Every lift, move and drop announcement of either companion, pointer or keyboard,
counts dataset positions against the dataset size. Both keep their list closed
to transfers: inside a [forDropListGroup] it joins nothing and connects to no
other list, because their reorder output describes a move within one dataset.
<div
forVirtualViewport
[virtualCount]="rows().length"
forVirtualReorder
(itemReorder)="onReorder($event)"
role="list"
aria-label="Rows"
>
<div *forVirtualFor="let row of rows()" role="listitem" forDraggable [dragData]="row.id">
{{ row.label }}
</div>
</div>
onReorder({ from, to }: ForVirtualReorderEvent): void {
this.rows.update((rows) => moveItemInArray(rows, from, to));
}
A custom integration that cannot use either companion must supply the same three
mechanisms itself: map window-relative to absolute indices, keep the lifted row
mounted for the duration of the drag, and step the keyboard target over the true
total count. The mapping reads the absolute index of every rendered row, in DOM
order. previousIndex is the lifted row's position in that list. currentIndex
is a position in the same list with the lifted row taken out: the target is the
absolute index found there (one past the last entry when the row lands at the
end), minus one when it is greater than the lifted row's own. Miss any one of the three and the failure is silent: an index that
addresses the wrong row, a lifted row recycled mid-drag, or a keyboard move that
stops at the window edge.
Virtual Reorder
Drag-reorder for a windowed *forVirtualFor list: it wraps [forDropList] and translates the window-relative drop into dataset-absolute indices, so a reorder is correct even when the lifted row scrolls out of the rendered window.
Apply [forVirtualReorder] on the same element as [forVirtualViewport] and mark each rendered row as [forDraggable] with a [dragData]. It is the drag-drop-side analogue of [forTableRowReorder] for non-table virtualized lists, and it never reorders the data itself (BYO-data): apply the move to your own array in the (itemReorder) handler. Vertical lists only.
Ships from the
forty-cdk/virtual-reordersecondary entry point, not fromforty-cdk/virtualization. It composes bothforty-cdk/virtualizationandforty-cdk/drag-drop, so keeping it here is what lets a consumer who only windows a list importforty-cdk/virtualizationwithout pulling drag-drop into their module graph.
Anatomy
<div
forVirtualViewport
[virtualCount]="rows().length"
[estimateSize]="44"
forVirtualReorder
(itemReorder)="onReorder($event)"
role="list"
aria-label="Rows"
style="height: 400px"
>
<div *forVirtualFor="let row of rows()" role="listitem" forDraggable [dragData]="row.id">
<span forDragHandle aria-hidden="true">⠿</span>
{{ row.label }}
</div>
</div>
Each row carries a [forDragHandle]. A row with no handle takes every touch move that starts on
it, and every touch on a virtualized list starts on a row, so a list of handle-less rows cannot be
scrolled by touch and (endReached) never fires for a touch user. With a handle, the rest of the
row pans the list and the handle starts the drag.
onReorder({ from, to }: ForVirtualReorderEvent): void {
this.rows.update((rows) => moveItemInArray(rows, from, to));
}
API
ForVirtualReorder
| Member | Type | Description |
|---|---|---|
itemReorder | output | Fires once per committed gesture with { from, to } absolute item indices. |
It re-exposes [forDropList]'s dir, disabled, autoScroll, boundary and lockAxis inputs through hostDirectives. It does not re-expose animateReorder or liveSort: the rows are positioned out of flow and keep their nodes across a reorder, so there is no sibling for a placeholder to part and no row for the drop to animate.
A row's [forDragPlaceholder] renders in the lifted row's own slot for the whole pointer drag: the coordinator copies the row's position, top, left, width, height and transform onto the placeholder's root element.
ForVirtualReorderEvent
| Property | Type | Description |
|---|---|---|
from | number | Previous absolute (dataset) index of the lifted item, 0-based. |
to | number | New absolute (dataset) index. Pass both to moveItemInArray. |
Keyboard
| Key | Behaviour | |
|---|---|---|
Space / Enter | Lift the focused row, or drop the lifted row. Focus follows the dropped row to its new index | |
ArrowUp / ArrowDown | Step the target one position | |
Home / End | Focus the first / last item of the dataset, scrolling it into view. While lifted, move the target there | |
PageUp / PageDown | Move focus by one window, scrolling the row into view. While lifted, step the target by one window | |
Escape / Tab | Cancel the gesture, scroll the origin back into view and keep focus on it | |
| Any other key | Ignored while a row is lifted. Ctrl / Cmd / Alt chords and function keys keep their browser meaning |
Every lift, move, drop and cancel is announced through the live announcer using the provideForDragDropDefaults message builders, so a scope override localizes them centrally. Pointer and keyboard gestures alike announce dataset positions counted against the dataset size, and name the row by its accessible text, so an aria-hidden handle glyph is not read out.
A [dragDisabled] row cannot be lifted but keeps Home / End, which reach the dataset ends from it as from any other row. Only a disabled list leaves those keys to the rows.
Only one gesture is live at a time. Focus leaving the viewport cancels a keyboard lift, and so does a press on any other row, so a drag that follows it is an ordinary pointer gesture. A press on the lifted row itself starts no pointer drag.
The lifted row carries drag-drop's data-dragging hook for the whole gesture (the coordinator owns the keyboard lift, so it marks the row on the drop list's behalf), and the viewport carries it too. Style either exactly as you would in a non-windowed [forDropList]. Each row's [forDraggable] emits dragStart and dragEnd for a keyboard gesture as it does for a pointer one, and dragStart.index is the dataset index.
What it adds over a bare [forDropList]
- Absolute-index translation: each rendered row's absolute index is read from the
data-indexattribute*forVirtualForemits, soitemReordercarries dataset indices andmoveItemInArrayover the full array moves the right item. - Lifted-row pinning: the lifted row is pinned into the window through the viewport's reordering index, so auto-scroll and a keyboard jump can both carry the window past it without recycling it. The pinned row keeps its DOM node, so it stays focused across the jump and the gesture survives to the drop.
- Dataset-wide keyboard reorder: keyboard stepping runs over the true total count, scrolling unmounted target rows into view rather than being confined to the window.
- Focus that follows the item: after a keyboard drop, focus moves to the row now rendering the dropped item at its new index, even when the window jumped past the row it was lifted from. Idle
Home/Endreach the dataset ends the same way.
The list is closed to transfers: placed inside a [forDropListGroup], it joins no group and connects to no other [forDropList], so no item moves into or out of it. itemReorder only describes a move within this dataset.
Windowed scrub
Hold Shift during a pointer drag to map the viewport onto the whole dataset (top edge → first item, bottom edge → last), so a single gesture drops the lifted item at an arbitrary far item without waiting for auto-scroll to reach it. The drop announcement names the position the item lands at. Without Shift, pointer resolution is unchanged.
Related
forty-cdk/virtualization: the viewport this adapter pins and scrolls.forty-cdk/drag-drop: the drop list it wraps.
Sortable list
<ul forDropList (dragDrop)="onDrop($event)">
@for (item of items(); track item.id) {
<li forDraggable [dragData]="item">{{ item.label }}</li>
}
</ul>
onDrop(event: ForDragDropEvent): void {
this.items.set(
moveItemInArray(this.items(), event.previousIndex, event.currentIndex),
);
}
Two-list transfer with forDropListGroup
<div forDropListGroup>
<ul forDropList (dragDrop)="onDrop($event)">
@for (item of active(); track item.id) {
<li forDraggable [dragData]="item">{{ item.label }}</li>
}
</ul>
<ul forDropList (dragDrop)="onDrop($event)">
@for (item of archived(); track item.id) {
<li forDraggable [dragData]="item">{{ item.label }}</li>
}
</ul>
</div>
onDrop(event: ForDragDropEvent): void {
if (event.previousContainer === event.container) {
this.updateList(event.container, (arr) =>
moveItemInArray(arr, event.previousIndex, event.currentIndex),
);
} else {
const result = transferArrayItem(
event.previousContainer === this.activeCtx ? this.active() : this.archived(),
event.container === this.activeCtx ? this.active() : this.archived(),
event.previousIndex,
event.currentIndex,
);
this.active.set(result.from);
this.archived.set(result.to);
}
}
Two-list transfer with explicit [connectedTo]
<ul forDropList #listA="forDropList" [connectedTo]="[listB]" (dragDrop)="onDrop($event)">
...
</ul>
<ul forDropList #listB="forDropList" [connectedTo]="[listA]" (dragDrop)="onDrop($event)">
...
</ul>
Scoped defaults
provideForDragDropDefaults configures drag-drop defaults for an injector subtree, either at the application root or in any component's providers array. They apply to [forDropList] and [forDraggable], and to the reorder coordinators [forListboxReorder], [forTreeNodeDrag], [forTableRowReorder] and [forVirtualReorder]. Partial overrides inherit unspecified keys from the parent scope (or the library fallbacks at the root).
| Key | Library fallback | Meaning | |
|---|---|---|---|
itemRoleDescription | 'sortable' | aria-roledescription of each item that can be lifted. An empty string drops the attribute. See Role description. | |
announceLift | '<label>, lifted. <index> of <total>.' | Announcement when an item is lifted. index / total describe the source list. | |
announceMove | '<label>, moved to position <index> of <total>.' | Announcement when the drop position changes. index / total describe the list under that position, which may be a connected list: then the fallback is '<label>, moved to <list>, position <index> of <total>.'. | |
announceDrop | '<label>, dropped at position <index> of <total>.' | Announcement on a committed drop. index / total describe the destination list. Into a connected list the fallback is '<label>, dropped in <list>, position <index> of <total>.'. | |
announceCancel | '<label>, movement cancelled.' | Announcement when a drag is cancelled. | |
autoScrollEdgeSize | 50 | Distance in px from a scroll edge that arms auto-scroll during a pointer drag. See Auto-scroll. | |
autoScrollMaxSpeed | 16 | Maximum scroll distance in px per animation frame while auto-scrolling. | |
liftKey | Shift+Enter, Ctrl+Space or Cmd+Space | Whether a keydown on a focused item lifts it into a keyboard reorder in [forListboxReorder], [forTreeNodeDrag] and [forTableRowReorder] (grid mode). |
itemRoleDescription is spoken by a screen reader, so translate it here. It accepts a string or a function returning one; a function can read a language signal, so the text follows a language the app sets or switches after bootstrap, as Localizing default text shows.
The four announcers are builder functions whose return value is spoken through an ARIA live region; return the sentence in your language. announceLift, announceMove and announceDrop receive (label, index, total, context), and announceCancel receives (label). label is the dragged item's name (see Item names) and index is the 1-based position being announced. total is the number of valid drop positions in the list the announcement describes, never a bare item count: the item count for a reorder inside one list, and one more than the target's item count for a transfer into a connected list, because the append gap past the last item is also a valid position. index therefore never exceeds total, and an empty transfer target announces 1 of 1. context is a ForDragDropAnnouncementContext: list is the accessible name of that list ('' when it has no aria-labelledby or aria-label) and transfer is true when it is not the list the item was lifted from. The fallbacks name the list only on a transfer, and say "another list" when it has no name. A builder that ignores context can leave the parameter out.
liftKey receives the KeyboardEvent and returns true when that key should lift the item. Shift+Enter is reserved by no operating system, while macOS and most IMEs claim Ctrl+Space / Cmd+Space before the page sees them. A keydown that belongs to an IME composition never lifts, whatever liftKey returns.
import { type ApplicationConfig } from '@angular/core';
import { provideForDragDropDefaults } from 'forty-cdk/defaults';
export const appConfig: ApplicationConfig = {
providers: [
provideForDragDropDefaults({
itemRoleDescription: 'reordenable',
announceLift: (label, index, total) => `${label}, levantado. ${index} de ${total}.`,
announceMove: (label, index, total, { list, transfer }) =>
transfer
? `${label}, movido a ${list || 'otra lista'}, posición ${index} de ${total}.`
: `${label}, movido a la posición ${index} de ${total}.`,
announceDrop: (label, index, total) =>
`${label}, soltado en la posición ${index} de ${total}.`,
announceCancel: (label) => `${label}, movimiento cancelado.`,
liftKey: (event) => event.key === 'Enter' && event.shiftKey,
}),
],
};
Wrapping in a design system
Subclass the root and re-provide FOR_DROP_LIST_CONTEXT with useExisting pointing at the subclass, since Angular does not inherit a directive's providers; Wrapping non-form roots walks the pattern.