Skip to content

Commit 2943932

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 3f2751f commit 2943932

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
@@ -578,6 +578,13 @@ describe('CdkDrag', () => {
578578
expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)');
579579
}));
580580

581+
it('should throw if attached to an ng-container', fakeAsync(() => {
582+
expect(() => {
583+
createComponent(DraggableOnNgContainer).detectChanges();
584+
flush();
585+
}).toThrowError(/^cdkDrag must be attached to an element node/);
586+
}));
587+
581588
});
582589

583590
describe('draggable with a handle', () => {
@@ -2766,6 +2773,15 @@ class NestedDropListGroups {
27662773
}
27672774

27682775

2776+
@Component({
2777+
template: `
2778+
<ng-container cdkDrag></ng-container>
2779+
`
2780+
})
2781+
class DraggableOnNgContainer {}
2782+
2783+
2784+
27692785
/**
27702786
* Component that passes through whatever content is projected into it.
27712787
* 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
@@ -323,6 +323,12 @@ export class CdkDrag<T = any> implements AfterViewInit, OnDestroy {
323323
.pipe(take(1))
324324
.subscribe(() => {
325325
const rootElement = this._rootElement = this._getRootElement();
326+
327+
if (rootElement.nodeType !== this._document.ELEMENT_NODE) {
328+
throw Error(`cdkDrag must be attached to an element node. ` +
329+
`Currently attached to "${rootElement.nodeName}".`);
330+
}
331+
326332
rootElement.addEventListener('mousedown', this._pointerDown, activeEventListenerOptions);
327333
rootElement.addEventListener('touchstart', this._pointerDown, passiveEventListenerOptions);
328334
this._handles.changes.pipe(startWith(null)).subscribe(() =>

0 commit comments

Comments
 (0)