Skip to content

Commit 31f0e6d

Browse files
crisbetommalerba
authored andcommitted
fix(drag-drop): throw better error when attaching to non-element node (#14221)
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 c99c512 commit 31f0e6d

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

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

+16
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,13 @@ describe('CdkDrag', () => {
579579
expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)');
580580
}));
581581

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

584591
describe('draggable with a handle', () => {
@@ -2809,6 +2816,15 @@ class NestedDropListGroups {
28092816
}
28102817

28112818

2819+
@Component({
2820+
template: `
2821+
<ng-container cdkDrag></ng-container>
2822+
`
2823+
})
2824+
class DraggableOnNgContainer {}
2825+
2826+
2827+
28122828
/**
28132829
* Component that passes through whatever content is projected into it.
28142830
* Used to test having drag elements being projected into a component.

src/cdk/drag-drop/drag.ts

+6
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)