Why Angular drag and drop cdk doesn't work?

2019-08-21 11:06发布

问题:

I am developing an Angular (v7.3.8) application and I need to implement a drag-and-drop horizontal list inside a specific page of my app, named 'test.page'. So I've used the new feature of Angular v7 cdk drag-and-drop, following this documentation:

https://material.angular.io/cdk/drag-drop/examples

In my app.module.ts I have

import { DragDropModule } from '@angular/cdk/drag-drop';
import ......

@NgModule({
    ....
    imports: [..., DragDropModule ],
    ... })

In my test.page.html I have:

<div cdkDropList cdkDropListOrientation="horizontal" class="example-list" (cdkDropListDropped)="drop($event)">
   <div class="example-box" *ngFor="let answer of answers" cdkDrag>{{answer}}</div>
</div>

And in my test.page.ts I have:

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

@Component({
  selector: 'app-test',
  templateUrl: './test.page.html',
  styleUrls: ['./test.page.css'],
})
export class TestPage implements OnInit {
    answers = [ ....... ];

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

    .....
    }

Unfortunately this code doesn't work for me (the items of the list don't move using drag-and-drop), and I don't uderstand why. Can anyone help me?