简体   繁体   中英

How to set up correctly cdk drag-drop for Angular?

see my steps

  1. npm install @angular/cdk

  2. in app.module.ts -> import { DragDropModule } from '@angular/cdk/drag-drop'; and import: [DragDropModule]

  3. next I want create drag and drops cards list. I created component for one card, and created parrent component when I will to get [{data}], produce card and pass current data for current card.

Parrent component TS:

import { Component, OnInit } from '@angular/core';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';


@Component({
  selector: 'app-groups',
  templateUrl: './groups.component.html',
  styleUrls: ['./groups.component.scss']
})
export class GroupsComponent implements OnInit {

  groups = [something data]

  constructor() { }

  ngOnInit(): void {
  }

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.groups, event.previousIndex, event.currentIndex);
  }
}

Parrent component HTML

<div cdkDropList class="groups" (cdkDropListDropped)="drop($event)">
    <div *ngFor="let group of groups">
        <app-group cdkDrag [data]="group"></app-group>
    </div>

</div>

But drag and drop on my card doesn't work, please help me)

i have warning (event cdkdroplistdropped is not emitted by any applicable directives nor by div element) for (cdkDropListDropped)="drop($event) in component HTML

Please change your ?.component.html code by this:

    <div cdkDropList class="groups" [cdkDropListData]="groups (cdkDropListDropped)="drop($event)">
        <div *ngFor="let group of groups" cdkDrag>
            {{ group }}
        </div>
    </div>

I tested in an application and it runs ok.

I solved this problem. This code is work!

<div class="groups" >
    <div cdkDropList class="groups__wrapper" (cdkDropListDropped)="drop($event)">
        <div *ngFor="let group of groups">
            <app-group cdkDrag cdkDragHandle [data]="group"></app-group>
        </div>
    </div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM