Drag and Drop with Angular Material

In this article, we will learn how to implement drag and drop using angular material.

Step 1:

Install angular material in your project using following command :

npm i @angular/material

Create one component :

ng  g  c  drag-and-drop

Step 2 :

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { DragAndDropComponent } from './drag-and-drop/drag-and-drop.component';
import { DragDropModule } from '@angular/cdk/drag-drop';


@NgModule({
  declarations: [
    AppComponent,
    DargAndDropComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    DragDropModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 3:

drag-and-drop.component.ts :

import { CdkDrag, CdkDragDrop, CdkDragEnter, CdkDragMove, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
import { identifierName } from '@angular/compiler';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-drag-and-drop',
  templateUrl: './drag-and-drop.component.html',
  styleUrls: ['./drag-and-drop.component.scss']
})
export class DragAndDropComponent implements OnInit {

  ngOnInit(): void {
   
  };
  Button = [
    'Button-1',
    'Button-2',
    'Button-3',
    'Button-4',
    'Button-5',
    'Button-6',
  ];
  public items: Array<number> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

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

  deletebtn(obj:any){
    if(confirm("Are you Sure.You Want Delete this Button?")){
        this.items = this.items.filter(items => items !== obj)
    }
}
  delete(obj:any) {
    if (confirm("Are you Sure.You Want Delete this Button?")) {
      this.Button = this.Button.filter(item => item !== obj);
    }
  
    }
   
    removebtn(){
      this.items = this.items.splice(0,this.items.length-1);
    }
    dropListReceiverElement?: HTMLElement;
    dragDropInfo?: {
      dragIndex: number;
      dropIndex: number;
    };

    add() {
      this.items.push(this.items.length + 1);
    }
  
    shuffle() {
      this.items.sort(function () {
        return 0.5 - Math.random();
      });
    }

    dragEntered(event: CdkDragEnter<number>) {
      const drag = event.item;
      const dropList = event.container;
      const dragIndex = drag.data;
      const dropIndex = dropList.data;
  
      this.dragDropInfo = { dragIndex, dropIndex };
      console.log('dragEntered', { dragIndex, dropIndex });
  
      const phContainer = dropList.element.nativeElement;
      const phElement = phContainer.querySelector('.cdk-drag-placeholder');
  
      if (phElement) {
        phContainer.removeChild(phElement);
        phContainer.parentElement?.insertBefore(phElement, phContainer);
  
        moveItemInArray(this.items, dragIndex, dropIndex);
      }
    }
    dragDropped(event: CdkDragDrop<number>) {
      if (!this.dropListReceiverElement) {
        return;
      }
      this.dropListReceiverElement.style.removeProperty('display');
      this.dropListReceiverElement = undefined;
      this.dragDropInfo = undefined;
    }
  }

Step 4:

drag-and-drop.component.html :

<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
    <div class="example-box" *ngFor="let item of Button" cdkDrag (dblclick)="delete(item)">{{item}}</div>
</div>


<button class="button" (click)="add()">Add</button>
<button class="button" (click)="removebtn()">Remove</button>

<div #dropListContainer class="example-container" cdkDropListGroup>
    <div *ngFor="let item of items; let i = index" cdkDropList [cdkDropListData]="i">
        <div cdkDrag [cdkDragData]="i" (cdkDragEntered)="dragEntered($event)" 
            (cdkDragDropped)="dragDropped($event)" (click)=deletebtn(item) class="example2-box">
            {{ item }}
        </div>
    </div>
</div>


Step 5:

now using below command  we can see the following output:

ng serve

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories