Angular CDK drag & drop cdk: Items change with animation

Discussão em 'Angular' iniciado por Naveh Elya, Fevereiro 16, 2025.

  1. Naveh Elya

    Naveh Elya Guest

    In angular 18 I have implemented a simple component using Angular drag & drop cdk (u can see better examples here):

    import {Component} from '@angular/core';
    import {
    CdkDrag,
    CdkDragDrop,
    CdkDragPlaceholder,
    CdkDropList,
    moveItemInArray,
    } from '@angular/cdk/drag-drop';

    @Component({
    standalone: true,
    selector: 'cdk-drag-drop-custom-placeholder-example',
    template: `<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
    @for (movie of movies; track movie) {
    <button (click)="moveUp(movie)">Up</button>
    <button (click)="moveDown(movie)">Down</button>
    <div class="example-box" cdkDrag>
    <div class="example-custom-placeholder" *cdkDragPlaceholder></div>
    {{movie}}
    </div>
    }
    </div>`,
    styleUrl: 'cdk-drag-drop-custom-placeholder-example.css',
    imports: [CdkDropList, CdkDrag, CdkDragPlaceholder],
    })
    export class CdkDragDropCustomPlaceholderExampleComponent {
    movies = [
    'Episode I - The Phantom Menace',
    'Episode II - Attack of the Clones',
    'Episode III - Revenge of the Sith',
    'Episode IV - A New Hope',
    'Episode V - The Empire Strikes Back',
    ];

    moveUp(item: string) {
    const index = this.movies.indexOf(item);
    moveItemInArray(this.movies, index, index - 1);
    }

    moveDown(item: string) {
    const index = this.movies.indexOf(item);
    moveItemInArray(this.movies, index, index + 1);
    }

    drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.movies, event.previousIndex, event.currentIndex);
    }
    }


    this simple code works and when dragging the movies around then there is animation which is moving them in the array,

    The problem starts when using the buttons up/down to move the items, they are switching places but instantly and with no animation at all.

    I would love to know how to enable the animation when changing the array manually. Thanks!

    Continue reading...

Compartilhe esta Página