Angular Material拖放-通过DragDrop服务创建拖放列表

时间:2019-06-21 23:37:57

标签: angular drag-and-drop angular-material-8

由于某些原因,我想通过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

我将不胜感激。

1 个答案:

答案 0 :(得分:0)

之所以不起作用,是因为可拖动项与下拉列表没有关联。 “创建”方法返回一个“引用”对象,您可以轻松地相互连接。

因此,解决问题的方法是:

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]);
  }
}