组件模块内的角度材料拖放操作

时间:2019-03-01 19:18:25

标签: angular drag-and-drop angular-material2 angular-components angular-module

我正在尝试在自定义组件模块后面使用Angular的CdkDropList和CdkDrag并进行排序。我发布了一个带有两个示例的stackblitz example here.。第一个示例使用我的自定义模块。第二个示例演示了相同的代码,但没有自定义模块。这两个示例都没有使用数组来构建CdkDrag区域,如Angular Material Docs Here所示。我想知道如何使用我的自定义组件来实现“示例1”以支持拖放拖放的重新排序,而无需使用数组来构建拖动列表。以下是基本组件设置。有关完整的代码示例,请参见stackblitz example

组件:

@Component({
  selector: 'dragPanel',
  styleUrls: ['drag.component.scss'], // reference not important
  template: `
    <div cdkDrag class="example-box">
         <b>{{ title }}</b>
         <ng-content></ng-content>
    </div>
  `,
})
export class DragComponent {
  @Input() title;
}

@Component({
  selector: 'dragListPanel',
  styleUrls: ['drag.component.scss'], // reference not important
  template: `
  <div #cdkList cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
      <ng-content></ng-content>
  </div> 
  `,
})
export class DragListComponent {
  @ContentChildren(DragComponent) dragPanels: QueryList<DragComponent>
  // @ViewChild(CdkDropList) cdklist: CdkDropList;

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

  ngAfterContentInit() {
    // Debugging
    this.dragPanels.forEach(panelInstance => {
      console.log(panelInstance);
    })
  }
}

模块:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DragDropModule } from '@angular/cdk/drag-drop'; 

// Custom components
import { DragComponent, DragListComponent } from './drag.component';
const components = [
  DragComponent,
  DragListComponent,
];

@NgModule({
  imports: [CommonModule, DragDropModule],
  declarations: components,
  exports: components,
  schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
})
export class UiDragpanelModule {}

要在您的app.component.html页面等中使用上述示例,

   <dragListPanel>
     <dragPanel title="One">data 1</dragPanel>
     <dragPanel title="Two">data 2</dragPanel>
     <dragPanel title="Three">data 3</dragPanel>
   </dragListPanel>

1 个答案:

答案 0 :(得分:1)

这似乎是CdkDropListContainer不是拖动元素的直接父元素的问题。如果我错了,有人可以纠正我,但是我相信ng-content容器是这种方法不起作用的原因,因为它们是边界。

  

下面提供了有关此问题的更多信息...   带有堆栈闪电的变通方法供您查看...此问题仍然存在,因此允许超出范围的绑定可能仍在研究中。

https://github.com/angular/material2/issues/14099


CdkDrag接受对CdkDropList的引用,您也许可以在其中传递引用。

  

dropContainer: CdkDropList 可拖动的容器是   的一部分。

https://material.angular.io/cdk/drag-drop/api#CdkDrag