Angular Material CDK DragAndDrop and dynamic components

21 Views Asked by At

I have dynamically created components. They render as expected and everything seems to work fine. Now I want to implement Angular Material CDK DragAndDrop. In order to do that I need to create custom service and make use of DragDrop service of CDK. Here is my service:

@Injectable({
providedIn: 'any',
})

export class DragAndDropService implements OnDestroy {
private dropListContainer: DropListRef | null;

private dragElements: DragRef[] = [];

private readonly dragDropService = inject(DragDrop);

private readonly destroy$ = new Subject<void>();

ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
}

createDropListContainer(elementRef: ElementRef<HTMLElement>): void {
    if (elementRef) {
        this.dropListContainer =
            this.dragDropService.createDropList(elementRef);

        this.dropListContainer.data = [];

        this.dropListContainer.dropped
            .pipe(takeUntil(this.destroy$))
            .subscribe((e) => {
                moveItemInArray(
                    e.container.data,
                    e.previousIndex,
                    e.currentIndex
                );
            });
    }
}

registerElementToDropContainer(elementRef: ElementRef<HTMLElement>): void {
    const newDragDropElement = this.dragDropService.createDrag(elementRef);
    this.dragElements.push(newDragDropElement);
    this.dropListContainer.withItems(this.dragElements);
}
}

Both container and dragable elements injects

eleRef: ElementRef<HTMLElement> = inject(ElementRef);

I can move items around in the container but after dropping the order is not updated.

0

There are 0 best solutions below