我想将Angular 8 Material Design cdkDrag与mat-grid-list一起使用,并且我做了一个小测试项目来尝试一下。
我的代码非常简单。 app.component.html:
<style>
.drag-handle {
position: absolute;
top: 10px;
left: 10px;
color: #ccc;
cursor: move;
width: 24px;
height: 24px;
}
</style>
<div cdkScrollable cdkDropList (cdkDropListDropped)="drop($event)">
<mat-grid-list cols="4" rowHeight="3:4" style="width: 25%;">{{number}}
<div cdkDrag *ngFor="let number of numbers">
<mat-grid-tile style="border: 1px solid green;">
{{number}}
<div class="drag-handle" cdkDragHandle>
<svg width="24px" fill="currentColor" viewBox="0 0 24 24">
<path
d="M10 9h4V6h3l-5-5-5 5h3v3zm-1 1H6V7l-5 5 5 5v-3h3v-4zm14 2l-5-5v3h-3v4h3v3l5-5zm-9 3h-4v3H7l5 5 5-5h-3v-3z">
</path>
<path d="M0 0h24v24H0z" fill="none"></path>
</svg>
</div>
</mat-grid-tile>
</div>
</mat-grid-list>
</div>
app.component.ts:
import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'drag-drop';
numbers: number[] = [];
constructor() {
for (let i = 0; i < 100; i++) {
this.numbers.push(i);
}
}
drop(event: CdkDragDrop<number[]>) {
moveItemInArray(this.numbers, event.previousIndex, event.currentIndex);
}
}
它有效,但不是我想要的方式。我可以拖动每个图块,但可以将其拖放到任何地方:
我想要的是保持瓷砖的美观并按以下网格排列:
拖放后如何将磁贴保持在网格中?