Drag And Drop In Angular

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

Step 1:

Install angular materail in your project using following command :

npm i @angular/material

Step 2:

In app.module.ts

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {DragDropModule} from '@angular/cdk/drag-drop';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';

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

Step 3:

In 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.scss']
})

export class AppComponent {
  values:any = [];
  constructor() { }

  removevalue(i: any) {
    this.values.splice(i, 1);
  }

  addNew() {
    this.values.push({ value: "" });
  }

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

}

Step 4:

In app.component.html

<section class="row">
  <button mat-raised-button color="primary" class="col-1 my-2" (click)="addNew()">
    Add New <i class="material-icons">add_circle_outline</i>
  </button>

  <div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
    <div class="example-box d-flex w-25" *ngFor="let value of values; let i = index" cdkDrag>
      <div class="w-100 drag-content">
        <input type="text" class="form-control" [(ngModel)]="value.value" #name="ngModel" name="value{{i}}">
      </div>
      <div class="delete-icon mb-5">
        <button mat-icon-button>
          <i class="material-icons" (click)="removevalue(i)" style="margin-bottom: 15px;">delete_outline</i>
        </button>
      </div>
    </div>
  </div>

  <div class="alert-text">
    <div *ngFor="let value of values;">
      <h3 class="border w-25">{{ value.value }}</h3>
    </div>
  </div>

</section>

Step 5 :

Now our above code is ready to run. we will use the following command:

ng serve

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories