Created
July 19, 2022 12:35
-
-
Save davidboothe/c2586e49f0b1d18a463eda3af80991df to your computer and use it in GitHub Desktop.
Service used to handle drag and drop across multiple components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Inject, Injectable} from '@angular/core'; | |
import {CdkDragDrop, CdkDragMove, CdkDragRelease, CdkDropList} from "@angular/cdk/drag-drop"; | |
import {DOCUMENT} from "@angular/common"; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class DragDropService { | |
public readonly DEFAULT_SCOPE = 'default'; | |
dropLists: {[scope: string]: CdkDropList[]} = {}; | |
currentHoverDropListId?: string; | |
dragData: any | null = null; | |
constructor(@Inject(DOCUMENT) private document: Document) { | |
this.dropLists[this.DEFAULT_SCOPE] = []; | |
} | |
public register(dropList: CdkDropList, scope: string = this.DEFAULT_SCOPE) { | |
this.dropLists[scope].push(dropList); | |
} | |
public unregister(dropList: CdkDropList, scope: string = this.DEFAULT_SCOPE) { | |
let index = this.dropLists[this.DEFAULT_SCOPE].findIndex(x => x == dropList); | |
if(index != -1) { | |
this.dropLists[scope].splice(index, 1); | |
} | |
} | |
getDropLists(scope: string = this.DEFAULT_SCOPE): CdkDropList[] { | |
return this.dropLists[scope]; | |
} | |
dragMoved(event: CdkDragMove<any>, scope: string = this.DEFAULT_SCOPE) { | |
let elementFromPoint = this.document.elementFromPoint( | |
event.pointerPosition.x, | |
event.pointerPosition.y | |
); | |
if (!elementFromPoint) { | |
this.currentHoverDropListId = undefined; | |
return; | |
} | |
let dropList = elementFromPoint.classList.contains('cdk-drop-list') | |
? elementFromPoint | |
: elementFromPoint.closest('.cdk-drop-list'); | |
if (!dropList) { | |
this.currentHoverDropListId = undefined; | |
return; | |
} | |
this.currentHoverDropListId = dropList.id; | |
this.dragData = event.source.data; | |
} | |
dropped(event: CdkDragDrop<any[]>) { | |
this.dragData = null; | |
} | |
dragReleased(event: CdkDragRelease) { | |
this.currentHoverDropListId = undefined; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment