Skip to content

Commit ebc6a2e

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 e048c2a commit ebc6a2e

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

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

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,7 @@ describe('CdkDrag', () => {
493493
expect(dragElement.style.touchAction)
494494
.not.toEqual('none', 'should not disable touchAction on when there is a drag handle');
495495
});
496+
496497
it('should be able to reset a freely-dragged item to its initial position', fakeAsync(() => {
497498
const fixture = createComponent(StandaloneDraggable);
498499
fixture.detectChanges();
@@ -545,7 +546,14 @@ describe('CdkDrag', () => {
545546
expect(fixture.componentInstance.endedSpy).toHaveBeenCalledTimes(1);
546547
}));
547548

548-
});
549+
it('should throw if attached to an ng-container', fakeAsync(() => {
550+
expect(() => {
551+
createComponent(DraggableOnNgContainer).detectChanges();
552+
flush();
553+
}).toThrowError(/^cdkDrag must be attached to an element node/);
554+
}));
555+
556+
});
549557

550558
describe('draggable with a handle', () => {
551559
it('should not be able to drag the entire element if it has a handle', fakeAsync(() => {
@@ -2580,6 +2588,14 @@ class ConnectedDropZonesWithSingleItems {
25802588
droppedSpy = jasmine.createSpy('dropped spy');
25812589
}
25822590

2591+
@Component({
2592+
template: `
2593+
<ng-container cdkDrag></ng-container>
2594+
`
2595+
})
2596+
class DraggableOnNgContainer {}
2597+
2598+
25832599
/**
25842600
* Component that passes through whatever content is projected into it.
25852601
* 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)