Sathishkumar
Sathishkumar

Reputation: 429

Angular : how remove dropped item in drag and drop angular/cdk

I develop some drag-and-drop UI using angular/CDK, Now I want to remove the dropped items from the droplist. How to remove the items from dropList

Typescript Code :

  drop(event: any) {
    console.log(event.container.data);

    console.log('drop');
    if (event.previousContainer === event.container) {
      console.log('move');
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      console.log('trans');
      copyArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
      console.log('trans2', this.done);
    }
  }

Please check the below stackblitz for ref.

https://stackblitz.com/edit/angular-ivy-msacoy?file=src%2Fapp%2Fapp.component.ts

I'm Expecting below behaviour

enter image description here

Upvotes: 1

Views: 856

Answers (1)

Flo
Flo

Reputation: 3127

UPDATE

The new question How to delete the Button is very easy.

First: in HTML part you know the item (or its id) from the ngFor loop. Set set this to the click event to the button.

<span class="badge bg-primary me-2"
      *ngFor="let it of item.items">
      {{ it.ruleName }}

      <button (click)="deleteMe($event, it)" class="btn btn-sm btn-danger">X</button>
</span>

So, then you have a done property which is an array. So loop the array and search in it's items[] for your id. Like this:

deleteMe(event: any, data: any) {
    console.log(data)
    for (let _done of this.done) {
      const findOne = _done.items.findIndex(f => f.ruleId === data.ruleId)
      if (findOne > -1) {
        _done.items.splice(findOne, 1)
        break;
      }
    }
  }

An all works as well!

----------------

It's simple. Instead of copyArrayItem() use the cdkDrags transferArrayItem() method. And the transfer will work as well.

Replace this one...

...
copyArrayItem(
  event.previousContainer.data,
  event.container.data,
  event.previousIndex,
  event.currentIndex
);
...

...to this:

...
transferArrayItem(
   event.previousContainer.data,
   event.container.data,
   event.previousIndex,
   event.currentIndex,
);
...

Upvotes: 1

Related Questions