1

出于某种原因,我想通过DragDrop服务应用 Angular Material Drag'n'Drop 功能。

正如文档中所写:https ://material.angular.io/cdk/drag-drop/api

DragDrop
Service that allows for drag-and-drop functionality to be attached to DOM elements.

Methods:
createDrag - turns an element into a draggable item
createDropList - turns an element into a drop list.

我能够向元素添加拖动功能,但我未能创建下拉列表功能:

import {Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
import {DragDrop, CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';


@Component({
  selector: 'cdk-drag-drop-sorting-example',
  templateUrl: 'cdk-drag-drop-sorting-example.html',
  styleUrls: ['cdk-drag-drop-sorting-example.css'],
})
export class CdkDragDropSortingExample implements AfterViewInit {
  @ViewChild('dropListArea', {static: false}) dropListArea: ElementRef;
  @ViewChild('dragable', {static: false}) dragable: ElementRef;
  @ViewChild('dragable2', {static: false}) dragable2: ElementRef;


  constructor(private dragDropService: DragDrop) {}

  ngAfterViewInit() {
    this.dragDropService.createDrag(this.dragable);
    this.dragDropService.createDrag(this.dragable2);
    this.dragDropService.createDropList(this.dropListArea);
  }
}

这是一个现场示例:https ://stackblitz.com/edit/angular-drtbaa?file=app/cdk-drag-drop-sorting-example.ts

我将不胜感激。

4

1 回答 1

3

它不起作用的原因是可拖动项目与下拉列表没有连接。“create”- 方法返回一个“ref”- 对象,您可以轻松地相互连接。

因此,您的问题的解决方案是:

import {Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
import {DragDrop, CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';

@Component({
  selector: 'cdk-drag-drop-sorting-example',
  templateUrl: 'cdk-drag-drop-sorting-example.html',
  styleUrls: ['cdk-drag-drop-sorting-example.css'],
})
export class CdkDragDropSortingExample implements AfterViewInit {
  @ViewChild('dropListArea', {static: false}) dropListArea: ElementRef;
  @ViewChild('dragable', {static: false}) dragable: ElementRef;
  @ViewChild('dragable2', {static: false}) dragable2: ElementRef;

  constructor(private dragDropService: DragDrop) {}

  public ngAfterViewInit() {
    const dragRef1 = this.dragDropService.createDrag(this.dragable);
    const dragRef2 = this.dragDropService.createDrag(this.dragable2);
    const dropListRef = this.dragDropService.createDropList(this.dropListArea);

    dropListRef.withItems([dragRef1, dragRef2]);
  }
}
于 2019-11-12T11:35:33.613 回答