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.
This commit is contained in:
Kristiyan Kostadinov
2018-12-05 00:40:30 +01:00
committed by mmalerba
parent c99c512106
commit 31f0e6d5ad
2 changed files with 22 additions and 0 deletions
+16
View File
@@ -579,6 +579,13 @@ describe('CdkDrag', () => {
expect(dragElement.style.transform).toBe('translate3d(100px, 100px, 0px)');
}));
it('should throw if attached to an ng-container', fakeAsync(() => {
expect(() => {
createComponent(DraggableOnNgContainer).detectChanges();
flush();
}).toThrowError(/^cdkDrag must be attached to an element node/);
}));
});
describe('draggable with a handle', () => {
@@ -2809,6 +2816,15 @@ class NestedDropListGroups {
}
@Component({
template: `
<ng-container cdkDrag></ng-container>
`
})
class DraggableOnNgContainer {}
/**
* Component that passes through whatever content is projected into it.
* Used to test having drag elements being projected into a component.
+6
View File
@@ -323,6 +323,12 @@ export class CdkDrag<T = any> implements AfterViewInit, OnDestroy {
.pipe(take(1))
.subscribe(() => {
const rootElement = this._rootElement = this._getRootElement();
if (rootElement.nodeType !== this._document.ELEMENT_NODE) {
throw Error(`cdkDrag must be attached to an element node. ` +
`Currently attached to "${rootElement.nodeName}".`);
}
rootElement.addEventListener('mousedown', this._pointerDown, activeEventListenerOptions);
rootElement.addEventListener('touchstart', this._pointerDown, passiveEventListenerOptions);
this._handles.changes.pipe(startWith(null)).subscribe(() =>