components icon indicating copy to clipboard operation
components copied to clipboard

Add cdk drag-and-drop features

Open jelbourn opened this issue 8 years ago • 94 comments

This issue tracks the high-level addition of drag-and-drop features to the cdk.

jelbourn avatar Dec 12 '17 19:12 jelbourn

@crisbeto, some feedback on the current cdk-experimental/drag-drop, which may or may not be useful to you:

1

The use of @Input() connectedTo: CdkDrop[]; for linking drop zones isn't the easiest API to work with. For example, say I have a large list of volunteers and a large list of roles the volunteers can be assigned to (both rendered with ngFor).

  • The volunteer list extends CdkDrop. Each volunteer list entry component has CdkDrag.
  • The roles list extends CdkDrop, each role entry component has CdkDrag as well as CdkDrop.
  • The user wants the ability to drag a volunteer onto a role to assign them.

Currently, I think you need to use @ViewChildren(RoleEntry) roleEntries in the parent component to grab all the role entry components and provide them as a [connectedTo]="roleEntries?.toArray()" input to the volunteer list (CdkDrop) component.

The main problem is that, since the role drop zones are created with ngFor, you cannot pass them as an array to the connectedTo input of the volunteer's list using a template reference variable.

A more ~~user~~ developer friendly solution might be to assign a string label to each drop zone. basically allowing something like "this volunteer entry (i.e. draggable) can be dropped on a zone labelled 'role' OR a zone labelled 'volunteer' (<-- for reordering) OR a zone labelled 'shift'". I think the ng2-dnd library makes use of a strategy like this.

2

The fact that CdkDragHandle must be a ContentChild of CdkDrag can be...annoying. Say I have a custom list component <my-list></my-list> and I have several different custom list entry components (<my-person></my-person>, <my-pet></my-pet>, etc) that can go within it. I may use the components like so (assuming <my-list> extends CdkDrop)

<my-list>
  <my-person *ngFor="let person of people" [person]="person" cdkDrag></my-person>
</my-list>

<my-person> already has, within its view, its own list of context buttons. I'd like to place the CdkDragHandle on one of those buttons, but CdkDrag wants me to do this:

<my-list>
  <my-person *ngFor="let person of people" [person]="person" cdkDrag>
    <button mat-icon-button cdkDragHandle><mat-icon>reorder</mat-icon></button>
  </my-person>
</my-list>

If there are many instances of <my-list><my-person></my-person></my-list> in an app, needing to insert the cdkDragHandle as ng-content can get annoying.

A workaround is to use @ViewChildren(CdkDragHandle) within <my-person> to grab the CdkDragHandle from within the view of <my-person>, then inject the instance of CdkDrag into <my-person>, then manually set the CdkDrag _handles property equal to the ViewChildren query. Something like:

  @ViewChildren(CdkDragHandle) _handles: QueryList<CdkDragHandle>;

  constructor(
    @Inject(CdkDrag) @Self() @Optional() public drag: CdkDrag,
  ) {}

  ngAfterViewInit() {
    this.drag._handles = this._handles;
  }

This strategy isn't ideal.

3

Currently, it's not possible (at least easily) to drop a draggable onto a drop zone and not transfer the draggable. Sometime's I'd like to simply use a drop to pass hidden data / trigger an output event while returning the dragged component to its original position.

4

In the same way that CdkDrop provides an @Input() data: T property for arbitrary data, it would be nice for CdkDrag to have an @Input() dragData: T property for arbitrary data.

Thanks!

Anyway, I realize that DragDropModule is a work in progress. It seems very likely some or all of these changes are already planned, but figured I'd call them out now as sore spots regardless.

Thanks!

jorroll avatar Jul 15 '18 15:07 jorroll

So far I have only one problem with cdk-experimental/drag-drop and that is that it doesn't scroll the parent element with overflow: auto; so you have to drag, drop at the top, scroll, drag, drop at the top..

fxck avatar Jul 17 '18 10:07 fxck

@thefliik:

For issue 1 maybe it's better to have some kind of "connectedGroup" parent directive to connect multiple directives?

For issue 2: I recognise that issue from the project where we built our own d/d solution. The limitation is that @ContentChildren does not query inside child component views. It could be solved by reversing the dependency: the CdkHndle gets the CdkDrag injected and triggers it. But in my solution this was not very easy to refactor because of.. several reasons.

What about MyPersonComponent extends CdkDrag? Then it is much easier to connect things. As a matter of fact, every <my-person> should aways be draggable, since you embed a handle in its view. ;) If not, then the handle should be external, or part of its content.

dirkluijk avatar Jul 17 '18 22:07 dirkluijk

Depending on extends on a component level in a library is normally not a good idea because the library consumers might want to extend their own classes for the reasons that are way bigger than just drag and drop. Then usually it becomes a pain to choose what of those 2 parent classes to extend which in the end will make people crying

smnbbrv avatar Jul 18 '18 05:07 smnbbrv

@dirkluijk I think the solution to issue 2 is to have CdkDragHandle inject the parent CdkDrag directive and register itself as a handle with the parent. This way, both use cases (i.e. View and Content) are accommodated. e.g.

export class CdkDragHandle {
  constructor(
    public el: ElementRef<HTMLElement>,
    @Inject(forwardRef(() => CdkDrag)) private dragDirective: CdkDrag,
  ) {}

  ngOnInit() {
    this.dragDirective._handles.push(this);
  }
}

I believe this strategy would (ahem) drop (😃) easily into the current CdkDrag implementation, which doesn't check it's handles until dragging begins.

Regardless of how it's done though, I'm confident in the material team's abilities to solve this annoyance if they decide they wish to do so.

What about MyPersonComponent extends CdkDrag?

It's already extending another class :-/ (a.k.a. @smnbbrv is exactly correct). But in general you are right, "every <my-person> should aways be draggable."

Regarding issue 1, I imagine there are a number of different approaches and I'm not particularly invested in any strategy other then to call out the fact that the current api is lacking. I'd probably start by trying to give each droppable a label (which I suppose could be a symbol, if strings make folks uncomfortable) and registering them with a service that can automatically connect them based on the labels. Labels seem like the most developer friendly approach while still being flexible, but I'm sure @crisbeto has given this a lot more thought.

jorroll avatar Jul 18 '18 10:07 jorroll

Regarding issue 1, something like this?

<!-- draggable with group 'foo' -->
<div cdkDrag [cdkDragGroup]="'foo'"></div>

<!-- dropzone which accepts 'foo' and 'bar' -->
<div cdkDropzone [cdkDragGroups]="['foo', 'bar']"></div>

Regarding issue 2: sounds ok.

However, I must say that having interaction between a directive outside a component with a directive inside a component feels somehow a bit dirty. Shouldn't they both live either in the same component, or outside it (for example in ng-content)?

e.g.

<!-- app.component.html -->
<foo-component cdkDrag>
  <div cdkDragHandle></div>
</foo-component>

I am not sure.

dirkluijk avatar Jul 18 '18 11:07 dirkluijk

The current version cdk-experimental/drag-drop does not work well with flex-layout

P/S Maybe it makes sense to make all the issues in "Projects" as with virtual scroll

zverbeta avatar Jul 18 '18 13:07 zverbeta

Having refactored angular-sortable-view to angular directives internally and seeing the discussion lately here, it's quite clear that people want something that was done before.

Maybe it would still be worthwhile to check their api and try to cover the functionality described there? Custom helpers, placeholders, groups, auto scrolling are all in there and the same pattern works well as angular directives with no need to extend custom classes (I am surprised to see this actually).

I'm fairly sure I could convince my manager to allow me to open source this internal lib and continue to contribute if it could become part of cdk as this is what we rely on and are quite happy with (overlays and tables are great!)

FDIM avatar Jul 18 '18 16:07 FDIM

@FDIM I imagine people would find value in that. Personally, I've already found a DnD library I'm quite happy with. I'm providing feedback not because I need these features now, but because I'd like to see CdkDragDrop succeed.

The library I'm using is AngularSkyhook, an implementation of the excellent react-dnd library (apparently used by Trello) to angular. Apparently, because the core of react-dnd was implemented as pure javascript (i.e. react-dnd-core), and doesn't even make use of the DOM, the library is particularly portable to many environments. Some examples of what AngularSkyhook can do (all written in Angular).

It's definitely a lower level library then what many may want (for instance, it does not come packaged with a sortable directive), but it has the benefit of relying on a very mature base and I'm finding it to be very flexible.

jorroll avatar Jul 18 '18 17:07 jorroll

That looks pretty good. How much does it add to the bundle size?

fxck avatar Jul 18 '18 17:07 fxck

Same here. As a matter of fact, I am currently making my own library, but I know drag/drop is not easy and want to share my insights.

@thefliik: I just adopted your strategy of registering "child directives" into "parent directives". Which works awesome.

edit: removed snippet, which was exactly like @thefliik posted before.. ;)

dirkluijk avatar Jul 18 '18 17:07 dirkluijk

That looks pretty good. How much does it add to the bundle size?

@fxck bundle size is not a major concern for my app, but I just got out my ruler and measured. It appears that, after the cli's optimizations, Skyhook increases my bundle size by 27kb. I have no frame of reference compared to other DND libraries. I'll also say that the answer will depend on what backend you use to power the drag/drops. It supports different backends depending on the environment you're in, i.e. touch, HTML5 API, custom, etc, and backends are offered as separate packages. I believe I've included both the touch and HTML5 backends.

jorroll avatar Jul 18 '18 18:07 jorroll

@thefliik any workaround for issue 1? I'm stucked!

thanks!

paulogr avatar Jul 20 '18 21:07 paulogr

@paulogr I described the workaround I came up with in the same paragraph I described issue 1, above.

Currently, I think you need to use @ViewChildren(RoleEntry) roleEntries in the parent component to grab all the role entry components and provide them as a [connectedTo]="roleEntries?.toArray()" input to the volunteer list CdkDrop component.

This being said, if you're working on a "real" project, you shouldn't be using cdk-experimental. ng2-dragula, angular skyhook, ng2-dnd, as well as countless other dnd packages exist that are ready to go today, unlike CdkDragDrop. For the "simple" solution, I'd recommend ng2-dnd except I don't think it's been updated to Angular6 (though there is a fork supporting Angular6 which hasn't been merged), so probably go with ng2-dragula. Angular skyhook is the best power user solution I've found.

Maybe @dirkluijk can offer you his library.

jorroll avatar Jul 20 '18 22:07 jorroll

@thefliik I'm trying to do this, but getting this error

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'connectedTo: '. Current value: 'connectedTo: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],

I have this structure

<div *ngFor="let w of activities?.weeks">
  <p>Semana {{ w.number }}</p>
  <sprts-calendar-week>
    <sprts-calendar-day *ngFor="let day of w.days; let i = index;" [day]="day">
      <cdk-drop [connectedTo]="dropZones.toArray()" [data]="day.activities" (dropped)="onDrop($event)">
        <sprts-calendar-activity *ngFor="let activity of day.activities" [activity]="activity" cdkDrag>
          <ng-template cdkDragPlaceholder>
            <div class="drag-placeholder"></div>
          </ng-template>
        </sprts-calendar-activity>
      </cdk-drop>
    </sprts-calendar-day>
  </sprts-calendar-week>
</div>

And I'm getting the dropzones like you sad

@ViewChildren(CdkDrop) dropZones: QueryList<CdkDrop> = new QueryList<CdkDrop>()

Any help?

Thanks very much.

paulogr avatar Jul 21 '18 02:07 paulogr

@paulogr Hmm. I'd probably try subscribing to the changes of @ViewChildren(CdkDrop) dropZones in ngAfterViewInit and saving an array of the dropzones to another public variable in the class (which you would then use in the component's view). If your component has ChangeDetectionStrategy.OnPush, all you should need to do next is ~~markAsDirty~~ markForCheck() (oops, I'd been reading the ivy source) whenever the subscription fires. If you're not using OnPush, it sounds like you'll need to add a debounce or something to ensure it doesn't fire too quickly. Something like:

this.subscriptions.push(
  this.dropZones.asObservable().subscribe(value => {
    this.dropZoneArray = value.toArray();
    this.cdr.markForCheck();
  })
)

(where cdr ^^^ is ChangeDetectorRef)

or

this.subscriptions.push(
  this.dropZones.asObservable().pipe(
    debounceTime(10),
  ).subscribe(value => {
    this.dropZoneArray = value.toArray();
  })
)

You might need to play around with the debounce time to find the right number.

jorroll avatar Jul 21 '18 12:07 jorroll

@thefliik Points 1 and 4 should be addressed once 5502e6f5d61e4f6b012498bbb341375b3fa0127d is out.

crisbeto avatar Jul 25 '18 21:07 crisbeto

Awesome. Looks like a good solution.

jorroll avatar Jul 26 '18 01:07 jorroll

Not sure if Point 1 is addressed the right way. Using unique IDs might be better than references but handling multiple dynamically rendered drop zones by referencing them to each other is a complex task. In my use case I have nested containers with multiple nodes and the containers can also be dragged - imagine a tree view, where you can rearrange any node. To set this up I would have to set every connectTo to refer to every other node on the screen.

I think a better approach would be to give the draggable some role (e.g. [role]="'node'") and to declare on the drop zone what roles it accepts without referencing the other zones (e.g. [accepts]="['node', 'containers']").

Or, perhaps have some function for the container where we can decide if the dragged item can be dropped into a container.

mucbits avatar Jul 27 '18 11:07 mucbits

Hi i just discovered this functionality in experimental and found it perfect ! But i didn't find a way to receive an event when an item is being dragged, i would love to have a 'drag_delta' event sending the item delta position !!! (we could then achieve resizing and moving very easily) Is it planned ? already there and i didn't see it in the source ? Thanks for your amazing work !

Angelinsky7 avatar Aug 07 '18 14:08 Angelinsky7