You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material V15中如何实现mat-chip-grid的拖拽功能?

Angular Material 15中mat-chip-grid实现拖拽的替代方案

Angular Material 15的mat-chip-grid确实没有内置旧版mat-chip-list的拖拽封装,不过可以直接基于Angular CDK的DragDrop模块手动实现,步骤如下:

  • 第一步:导入CDK DragDrop模块
    在你的功能模块(比如AppModule或者对应组件的模块)中导入DragDropModule:

    import { DragDropModule } from '@angular/cdk/drag-drop';
    import { MatChipsModule } from '@angular/material/chips';
    
    @NgModule({
      imports: [
        MatChipsModule,
        DragDropModule
        // 其他已导入模块
      ]
    })
    export class YourModule {}
    
  • 第二步:修改模板结构
    用cdkDropList包裹mat-chip-grid,并给每个mat-chip-row添加cdkDrag指令:

    <div cdkDropList (cdkDropListDropped)="handleChipDrop($event)">
      <mat-chip-grid aria-label="可拖拽标签组">
        <mat-chip-row 
          *ngFor="let chip of chipList; let idx = index" 
          cdkDrag
        >
          {{ chip.label }}
          <button matChipRemove (click)="removeChip(idx)">
            <mat-icon>close</mat-icon>
          </button>
        </mat-chip-row>
      </mat-chip-grid>
    </div>
    
  • 第三步:实现拖拽排序逻辑
    在组件类中导入必要的工具方法,完成拖拽后的数组重排:

    import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
    
    export class YourComponent {
      chipList = [
        { label: '标签1' },
        { label: '标签2' },
        { label: '标签3' }
      ];
    
      handleChipDrop(event: CdkDragDrop<any[]>) {
        moveItemInArray(this.chipList, event.previousIndex, event.currentIndex);
      }
    
      removeChip(index: number) {
        this.chipList.splice(index, 1);
      }
    }
    
  • 可选:优化拖拽预览样式
    默认的拖拽预览可能和mat-chip-row的样式有差异,可以通过cdkDragPreview自定义预览模板:

    <mat-chip-row 
      *ngFor="let chip of chipList; let idx = index" 
      cdkDrag
    >
      <ng-template cdkDragPreview>
        <mat-chip-row class="drag-preview">
          {{ chip.label }}
        </mat-chip-row>
      </ng-template>
      {{ chip.label }}
      <button matChipRemove (click)="removeChip(idx)">
        <mat-icon>close</mat-icon>
      </button>
    </mat-chip-row>
    

    对应的CSS调整:

    .drag-preview {
      opacity: 0.9;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
      cursor: move;
    }
    

旧版mat-chip-list的拖拽功能本质也是基于Angular CDK封装的,mat-chip-grid作为替代组件没有内置这层封装,直接用CDK的DragDrop就能完全实现相同的拖拽排序效果。

内容的提问来源于stack exchange,提问作者holegeek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 13:32:55