Search code examples
angulardrag-and-dropangular-materialangular7

How to use Angular 7 cdkDropList between components?


I have a list of items (students) in a mat-list component on the left side of my screen (general list). I also have a list of class-room Components on the right side of my screen. In each class-room Component, there is a mat-list of students.

I want to be able to drag students from to the general List to one of the students lists contained inside any of the class-room Component using the new Drag&Drop API of angular material

the pseudo code looks like this:

<mat-list #studentsList="cdkDropList" cdkDropList [cdkDropListData]="students">
  <mat-list-item cdkDrag *ngFor="let student of studentes">
    {{student.name}}
  </mat-list-item>
</mat-list>

<div class="right-panel>
  <app-class-room *ngFor="let cr of classRooms" [classRoom]="cr"></app-class-room>
</div>

Obviously, I can't use the [cdkDropListConnectedTo] input on the general list as I don't have access to the student list inside the Class-room Component. How should I proceed?


Solution

  • You can use string instead of reference as mentionned in the API documentation :

    @Input('cdkDropListConnectedTo') connectedTo: (CdkDropList | string)[] | CdkDropList | string

    Other draggable containers that this container is connected to and into which the container's items can be transferred. Can either be references to other drop containers, or their unique IDs.

    I made an example using a list of all dropable elements ids.

    allDropLists = [ 'studentsList', ...this.classRooms
     .map(_ => _.name)];
    

    Which I pass to the ClassRoomComponent as an input :

    <app-class-room
        *ngFor="let classRoom of classRooms" 
        [classRoom]="classRoom" [allDropLists]="allDropLists">
    

    The complete running example is here.