In a form builder using Angular CDK drag-drop, how do you copy field types from a palette onto a canvas without emptying or reordering the palette?
answer
- move is the default between lists
- a helper that leaves the source alone
- same reference, shared edits
- something stays behind while dragging
- stop the palette sorting itself
basics
~20 sConnect the Angular CDK palette list one way to the canvas, set cdkDropListSortingDisabled and cdkDropListHasAnchor on the palette, and in the canvas drop handler insert a new field instance rather than the palette's own object, which copyArrayItem would share.
solid answer
~40 sBetween connected lists the Angular CDK moves items, so the palette needs four settings. Connect it to the canvas with `cdkDropListConnectedTo` and leave the canvas unconnected, so canvas fields cannot be dragged back. Add `cdkDropListSortingDisabled` so users cannot reorder the palette, and `cdkDropListHasAnchor` (CDK 20.1 and later) so a copy of the field type stays visible in the palette while one is being dragged. In the canvas's `cdkDropListDropped` handler, reorder with `moveItemInArray` when `previousContainer === container`; otherwise insert into the canvas. `copyArrayItem` inserts the **same object reference** and leaves the palette untouched, which suits immutable values, but a form field needs its own `id` and settings, so build a new object from `event.item.data`, or every copied Email field would share one label.
code
ts · 37 linesimport {Component, signal} from '@angular/core';
import {CdkDrag, CdkDragDrop, CdkDropList, moveItemInArray} from '@angular/cdk/drag-drop';
interface FieldType { kind: 'text' | 'email' | 'date'; label: string; }
interface Field extends FieldType { id: string; required: boolean; }
@Component({
selector: 'app-form-designer',
imports: [CdkDropList, CdkDrag],
template: `
<ul cdkDropList cdkDropListSortingDisabled cdkDropListHasAnchor
[cdkDropListConnectedTo]="[canvasList]">
@for (type of palette; track type.kind) {
<li cdkDrag [cdkDragData]="type">{{ type.label }}</li>
}
</ul>
<ol cdkDropList #canvasList="cdkDropList" (cdkDropListDropped)="drop($event)">
@for (field of canvas(); track field.id) { <li cdkDrag>{{ field.label }}</li> }
</ol>
`,
})
export class FormDesigner {
readonly palette: FieldType[] = [
{kind: 'text', label: 'Text'}, {kind: 'email', label: 'Email'}, {kind: 'date', label: 'Date'},
];
readonly canvas = signal<Field[]>([]);
drop(e: CdkDragDrop<unknown, unknown, FieldType>) {
const next = [...this.canvas()];
if (e.previousContainer === e.container) {
moveItemInArray(next, e.previousIndex, e.currentIndex);
} else {
next.splice(e.currentIndex, 0, {...e.item.data, id: crypto.randomUUID(), required: false});
}
this.canvas.set(next);
}
}go deeper
Recall that connected lists move items by default, and that copyArrayItem inserts an item into the target while leaving it in the source.
Explain the palette inputs: a one-way connection, cdkDropListSortingDisabled to freeze its order and cdkDropListHasAnchor to keep a visible anchor during the drag.
Show why copyArrayItem shares references and why form fields need fresh instances with their own ids, and place the handler on the canvas, where the drop event fires.
Frame the palette as a catalogue of types and the canvas as a document of instances: keeping those two models separate is what makes undo, saving and versioning tractable.
## Moving is the default In the Angular CDK, two connected `cdkDropList` elements **move** items between them: the drag takes the item out of the source list visually, and the usual handler calls `transferArrayItem`, which removes it from the source array. A form builder wants the opposite for its **palette**: dragging the Email field type onto the **canvas** must leave Email in the palette, ready to be used again, and the palette's order should never change. That takes four pieces: a one-way connection, two palette inputs and a handler that inserts a *new* field. ## The palette inputs | Input on the palette list | Effect | |---|---| | `[cdkDropListConnectedTo]="[canvasList]"` | Palette items may enter the canvas; with no connection back, canvas fields cannot be dropped on the palette | | `cdkDropListSortingDisabled` | Users cannot reorder the palette; a palette item that is not dropped anywhere returns to its starting position | | `cdkDropListHasAnchor` | While an item is dragged out, an **anchor** stays in the palette at its starting position, styled through `.cdk-drag-anchor`; it is removed if the item comes back | **`cdkDropListHasAnchor`** was added in CDK 20.1. Without it, the dragged field type visually disappears from the palette during the drag, even though the data is untouched, which makes the palette look broken. The angular.dev guide describes exactly this combination of an anchor and disabled sorting for a list users copy from without reordering it. If the lists are connected both ways, or live in a `cdkDropListGroup`, put `[cdkDropListEnterPredicate]` returning `false` on the palette as well. The CDK still lets a palette item return to the palette, because an item may always go back to the list it started in, but canvas fields are kept out. ## The handler on the canvas The drop event fires on the list where the item lands, so the handler lives on the canvas: 1. If `event.previousContainer === event.container`, the user is reordering canvas fields: call `moveItemInArray`. 2. Otherwise the item came from the palette: create a **new field instance** from the palette entry and insert it at `event.currentIndex`. 3. Read the palette entry through `event.item.data`, which requires `[cdkDragData]="type"` on each palette row, or through `event.previousContainer.data[event.previousIndex]` when the palette binds `cdkDropListData`. ## Why not just copyArrayItem? **`copyArrayItem(source, target, sourceIndex, targetIndex)`** inserts `source[sourceIndex]` into the target array and leaves the source untouched. The CDK's own copy example uses it for a shopping cart of strings, and for immutable values such as strings it is all you need. The catch is that it copies the **reference**, not the object: - Every Email field on the canvas would be the *same* object as the palette entry, so renaming one field's label renames them all, including the palette. - Two copies of one field type would have no distinct `id`, so tracking them in `@for`, binding form controls to them or saving them becomes ambiguous. - Settings such as `required` or a placeholder text belong to one field on the canvas, not to its type. So for a form builder, build the instance yourself, for example `{...type, id: crypto.randomUUID(), required: false}`, and insert it with `splice`, or into a copy of the array when the canvas lives in a signal. `copyArrayItem` is the right helper when the items really are interchangeable values. ## Common failure modes - **The palette loses entries:** the handler used `transferArrayItem`, which removes the type from the palette array. - **All copies change together:** `copyArrayItem` shared one object reference between the palette and every canvas field. - **The palette reorders under the user:** `cdkDropListSortingDisabled` is missing. - **The dragged type vanishes from the palette mid-drag:** `cdkDropListHasAnchor` is missing, or the CDK is older than 20.1. - **Nothing happens on drop:** the handler is bound on the palette instead of the canvas. ## What else to check - Like the other helpers, `copyArrayItem` mutates the target array in place, so signal state still needs a copy. - Deleting a field from the canvas is a separate interaction, often a remove button or a connected trash list whose handler splices the field out. - Style `.cdk-drop-list-receiving` on the canvas so users see where field types can go.
- What does cdkDropListHasAnchor change, given that the palette's array is never modified anyway?It changes only what the user sees during the drag. Without it, the dragged field type leaves the palette visually and its slot closes up until the drop, so the palette looks as if it lost an item. With it, the CDK leaves an anchor element at the starting position, styled through `.cdk-drag-anchor`, and removes it if the item returns. The input exists since CDK 20.1.
- Why does the drop handler belong on the canvas and not on the palette?The CDK emits `cdkDropListDropped` from the list where the item is dropped. A field type dropped on the canvas produces the event on the canvas, with the palette as `previousContainer`. A handler only on the palette would never see those drops; it would fire only for a palette item released back in the palette, which needs no data change at all.
- When is copyArrayItem exactly the right tool?When the items are interchangeable values whose identity does not matter, such as strings, numbers or frozen objects that are never edited, for example tags dropped onto a post. Then sharing the reference is harmless and the helper is one line. As soon as each copy needs its own id or editable state, create a new object instead.
- copyArrayItem deep-clones the item, so each canvas field is independent.
- cdkDropListHasAnchor makes the CDK copy the item into the target array.
- cdkDropListSortingDisabled on the palette also stops items leaving it.
- The copy handler belongs on the palette, the list the field type came from.
- Without cdkDropListHasAnchor the palette array loses the dragged entry.
Assumes Angular CDK 22; cdkDropListHasAnchor and the .cdk-drag-anchor class were added in CDK 20.1 and are missing from earlier versions.