Vasilii Maslov
Vasilii Maslov

Reputation: 31

Angular Material drag n drop CDK remove element on list

How can I remove a list item? I tried removing the item from the array associated with the list, but this breaks the list altogether.

I use Angular (with Material) 9.0

Upvotes: 1

Views: 7703

Answers (1)

Vasilii Maslov
Vasilii Maslov

Reputation: 31

I have 2 lists. When I drag an item from the first list (sequenceOfSlides) to the second (listOfSlides), I delete it, and from the second to the first I copy it. The problem was that I removed the elements from the array associated with the list with its full replacement. With @Eliseo, I began to remove elements from the original array without changing the link to it. Template:

<div class="row" cdkDropListGroup>
        <div class="col-6">
            <div
                    id="sequenceOfSlidesElement"
                    cdkDropList
                    [cdkDropListData]="sequenceOfSlides"
                    class="example-list"
                    (cdkDropListDropped)="drop($event)">
                <div
                        class="example-box"
                        *ngFor="let item of sequenceOfSlides"
                        cdkDrag>
                    {{item.ruName}}
                </div>
            </div>
        </div>

        <div class="col-6">
            <div
                    id="listOfSlidesElement"
                    cdkDropList
                    [cdkDropListEnterPredicate]="noReturnPredicate"
                    [cdkDropListData]="listOfSlides"
                    class="example-list"
                    (cdkDropListDropped)="drop($event)">
                <div
                        class="example-box"
                        *ngFor="let item of listOfSlides"
                        cdkDrag>
                    {{item.ruName}}
                </div>
            </div>
        </div>
    </div>

Component:

 drop(event: CdkDragDrop<ISlide[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      if (event.container.id === 'sequenceOfSlidesElement') {
        copyArrayItem(event.previousContainer.data,
          event.container.data,
          event.previousIndex,
          event.currentIndex);
      } else {
        this.sequenceOfSlides.splice(event.previousIndex, 1);
      }
    }
  }

Upvotes: 1

Related Questions