After implementing a ngFor loop in my component to render multiple CdkDrag elements from an array, I encountered the issue of their positions updating when deleting one element and splicing the array. Is there a way to prevent this unwanted position update?
I attempted to retrieve the freeDragPosition of each draggable element before deletion and reset their positions, but unfortunately, it did not work.
Shown below is my app.component.html code snippet:
<div class="container" id="container">
<div *ngFor="let f of fields; let i = index;"
class="textField"
[attr.data-guid]="f.guid"
(mouseenter)="onFieldHover($event)"
cdkDrag
cdkDragBoundary="#container"
(cdkDragEnded)="onDragEnded($event)"
[cdkDragFreeDragPosition]="f.position">
<div class="textField-inner">
<span style="color: hotpink; font-weight: bold">{{f.guid}}</span>
</div>
<div class="textField-options">
<div class="textField-move" cdkDragHandle>
<svg width="24px" fill="currentColor" viewBox="0 0 24 24">
<path d="M10 9h4V6h3l-5-5-5 5h3v3zm-1 1H6V7l-5 5 5 5v-3h3v-4zm14 2l-5-5v3h-3v4h3v3l5-5zm-9 3h-4v3H7l5 5 5-5h-3v-3z"></path>
<path d="M0 0h24v24H0z" fill="none"></path>
</svg>
</div>
<div class="textField-remove">
<i class="fas fa-trash-alt" (click)="onRemoveTextField(i)"></i>
</div>
</div>
</div>
</div>
<button type="button" (click)="onTextFieldAdded()">Add a field</button>
The corresponding app.component.ts file looks like this:
import { Component } from '@angular/core';
import {CdkDrag, CdkDragEnd} from '@angular/cdk/drag-drop';
// Component definition goes here
export class Field{
// Field class properties defined here
}
To resolve this issue, I aim to keep the elements in their current positions even after deleting one of them.
You can view a GIF demonstration of the problem here.
A working example on StackBlitz can be accessed here.