首页 > 解决方案 > How to use cdkDrag together with mat-grid

问题描述

I would like to use Angular 8 Material Design cdkDrag together with mat-grid-list and I have made a small test project to try it out.

My code is fairly simple. 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);
    }
}

It works, but not the way I would like. I can drag each tile, but I can drop it anywhere:

enter image description here

What I would like is to keep the tiles nice and ordered in a grid like:

enter image description here

How can I keep the tiles in a grid after I drag and drop them?

标签: angularangular-material

解决方案


推荐阅读