【问题标题】:Angular 7 - Drag drop with parent droppable containerAngular 7 - 使用父可放置容器拖放
【发布时间】:2019-04-02 09:55:26
【问题描述】:

我正在尝试使用新的 Angular 7 CDK 拖放来移动我网站中动态添加的元素列表。

使用 this example,取自 angular 文档示例并根据我的需要进行修改,您可以看到我有一个带有可放置容器的元素列表。

问题是当可拖动元素是从另一个组件生成时,它们并没有把父droppable作为引用的droppable容器来使用。相反,CDK Draggable 对象中的可放置容器属性是null

我尝试从CdkDrag 指令中设置cdkDragRootElement 属性,以检查我是否可以以某种方式引用父元素,但它使元素移动整个父元素。这不是预期的行为。

也许我错过了 CDK 可拖动属性或 CDK 可放置容器中以引用列表元素中的父可放置列表?

这是示例中的“相关”代码:

cdk-drag-drop-sorting-example.html

<div cdkDropList class="example-list">
  <app-test></app-test>
</div>

test/test.component.ts

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

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
  movies = [
    'Episode I - The Phantom Menace',
    'Episode II - Attack of the Clones',
    'Episode III - Revenge of the Sith',
    'Episode IV - A New Hope',
    'Episode V - The Empire Strikes Back',
    'Episode VI - Return of the Jedi',
    'Episode VII - The Force Awakens',
    'Episode VIII - The Last Jedi'
  ];

  constructor() { }

  ngOnInit() {
  }

  drop(event: CdkDragDrop<string[]>) {
    console.log(event);
    /*moveItemInArray(this.movies, event.previousIndex, event.currentIndex);*/
  }

}

test/test.component.html

<div class="example-box" *ngFor="let movie of movies" cdkDrag (cdkDragDropped)="drop($event)">
  {{movie}}
</div>

编辑

预期结果:

cdk-drag-drop-sorting-example.html

<div cdkDropList class="example-list">
  <app-test></app-test>
</div>

test/test.component.html

<div class="example-box" *ngFor="..." cdkDrag cdkDropList=".example-list">
  {{movie}}
</div>

通过父母找到选择器并检查它是否具有cdkDropList指令/实例并将其附加到cdkDrag

【问题讨论】:

    标签: angular typescript drag-and-drop angular-material angular-cdk


    【解决方案1】:

    属性cdkDropList 必须位于app-test - 这是包含您的项目列表的 DOM 元素

    【讨论】:

    • 这不起作用。可拖动元素仍然不知道谁是下拉列表容器。
    【解决方案2】:

    问题是当您在组件级别添加时,DOM 无法识别 cdkdropList。有两种方法可以做到这一点。
    1) 如果我们将 cdkDragList 移动到测试组件内。这很明显,您可能不感兴趣。
    2) 您可以使用 DragDrop 服务在父级添加拖动列表。 Angular CDK 7.3.7 发布了这种使用拖放作为服务的功能。


    参考 stackblitz https://stackblitz.com/edit/angular-ngtemplate-reorder-7i6uuk?file=src%2Fapp%2Fapp.component.ts 使用服务实现拖放。

    【讨论】:

    • 我会尽可能测试它。当我写这篇文章时,CDK 版本是 7.0,我无法实现。
    猜你喜欢
    • 1970-01-01
    • 2019-06-08
    • 2019-05-05
    • 2012-11-28
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    相关资源
    最近更新 更多