I am trying to build a drag and drop functionality which drags some formControls inside formArray. On dropping the item it fires the event with correct information but noticing on the UI, the items don’t drop to the correct position (currentIndex). As shown in this video recording- video .
Below are the code snippets for reference-
<div class="drag-boundary py-1" cdkDropList (cdkDropListDropped)="drop($event)">
<div *ngFor="let question of questions.controls; let i = index"
class="my-1.5 block w-full form-input py-3 bg-gray-700 border-gray-600 text-white font-normal focus:outline-none cursor-pointer rounded"
cdkDragBoundary=".drag-boundary" cdkDragLockAxis="y" cdkDrag>
<ng-container class="grid" formArrayName="questions">
<div [formGroupName]="i">
<div class="w-full">
<div class="flex items-center">
<mat-icon>drag_indicator</mat-icon>
<span class="text-white font-normal">{{ i + 1}}.</span>
<input type="text"
class="block w-full form-input bg-gray-700 border-gray-600 text-white font-normal focus:outline-none cursor-move"
formControlName="text" readonly />
</div>
</div>
</div>
</ng-container>
</div>
</div>
drop(event: CdkDragDrop<string[]>): void {
console.log(event);
const questionsControls = this.journeyForm.get('questions') as FormArray;
this.moveItemInFormArray(
questionsControls,
event.previousIndex,
event.currentIndex,
);
}
moveItemInFormArray(
formArray: FormArray,
fromIndex: number,
toIndex: number,
): void {
const dir = toIndex > fromIndex ? 1 : -1;
const item = formArray.at(fromIndex);
for (let i = fromIndex; i * dir < toIndex * dir; i = i + dir) {
const current = formArray.at(i + dir);
formArray.setControl(i, current);
}
formArray.setControl(toIndex, item);
(this.journeyForm.get('questions') as FormArray).controls = [
...(this.journeyForm.get('questions') as FormArray).controls,
];
}
CSS for Drag Boundary
drag-boundary
height: 100%
moveItemInFormArray() method is doing its job well and good.
Can someone please help me in resolving this issue? I am stuck here for days, even I am not aware of why it is happening.
Your efforts will be appreciated. Thanks in advance.
I implemented the same functionality somewhere else and it is working fine in that case.
I am just expecting the dragged item should be dropped correctly on UI side. On dropping they shouldn’t drop on unwanted positions as shown in the attached video.