Search code examples
angularangular-materialangular7angular-cdk

Is it possible to put a cdkDrag inside a mat-select?


I have a simple mat-select element:

<mat-form-field>
  <mat-select placeholder="Favorite food">
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

where in the TypeScript, foods is:

  foods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];

Is it possible use cdkDrag inside a mat-select element? I'm trying to achieve something like this:

<mat-form-field>
  <mat-select placeholder="Favorite food">
    <div cdkDropList>
      <div *ngFor="let food of foods">
        <span cdkDragHandle>$$$</span>
        <mat-option [value]="food.value" cdkDrag>
          {{food.viewValue}}
        </mat-option>
      </div>
     </div>
  </mat-select>
</mat-form-field>

but I'm having trouble getting the dropdown items to drag. Please help!


Solution

  • Yes! It is possible:

    <mat-form-field>
      <mat-select placeholder="Favorite food" multiple>
        <div cdkDropList (cdkDropListDropped)="drop($event)">
          <mat-option *ngFor="let food of foods" [value]="food.value" cdkDrag>
            {{food.viewValue}}
            <span cdkDragHandle>$$$</span>
          </mat-option>
          </div>
      </mat-select>
    </mat-form-field>
    

    It looks like the trick is to wrap your mat-options inside a cdkDropList div, so that the drop event (cdkDropListDropped) will fire reliably. Working StackBlitz.