Skip to content

Commit 57b09bb

Browse files
committed
fix(drag-drop): throw better error when attaching to non-element node
Currently if somebody attaches a `cdkDrag` to a non-element node (e.g. an `ng-container`), a cryptic error will be thrown. These changes log a proper error so it's easier to debug.
1 parent 3982e9e commit 57b09bb

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/cdk/drag-drop/drag.spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,13 @@ describe('CdkDrag', () => {
567567
expect(dragElement.style.transform).toBe('translate3d(13px, 37px, 0px)');
568568
}));
569569

570+
it('should throw if attached to an ng-container', fakeAsync(() => {
571+
expect(() => {
572+
createComponent(DraggableOnNgContainer).detectChanges();
573+
flush();
574+
}).toThrowError(/^cdkDrag must be attached to an element node/);
575+
}));
576+
570577
});
571578

572579
describe('draggable with a handle', () => {
@@ -2696,6 +2703,15 @@ class NestedDropListGroups {
26962703
}
26972704

26982705

2706+
@Component({
2707+
template: `
2708+
<ng-container cdkDrag></ng-container>
2709+
`
2710+
})
2711+
class DraggableOnNgContainer {}
2712+
2713+
2714+
26992715
/**
27002716
* Component that passes through whatever content is projected into it.
27012717
* Used to test having drag elements being projected into a component.

src/cdk/drag-drop/drag.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,12 @@ export class CdkDrag<T = any> implements AfterViewInit, OnDestroy {
307307
.pipe(take(1))
308308
.subscribe(() => {
309309
const rootElement = this._rootElement = this._getRootElement();
310+
311+
if (rootElement.nodeType !== this._document.ELEMENT_NODE) {
312+
throw Error(`cdkDrag must be attached to an element node. ` +
313+
`Currently attached to "${rootElement.nodeName}".`);
314+
}
315+
310316
rootElement.addEventListener('mousedown', this._pointerDown, activeEventListenerOptions);
311317
rootElement.addEventListener('touchstart', this._pointerDown, passiveEventListenerOptions);
312318
this._handles.changes.pipe(startWith(null)).subscribe(() =>

0 commit comments

Comments
 (0)