Open In App

Angular PrimeNG Drag and Drop Events

Last Updated : 14 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Angular PrimeNG is a UI component library for Angular Applications. It offers many pre-built themes and UI components for a variety of tasks like inputs, menus, charts, Buttons, etc. In this article, we will learn about Angular PrimeNG Drag and Drop Events.

The Drag and Drop directives (pDraggable and pDroppable) are used to apply drag and drop behavior to any element. The three events of the Drag and Drop are listed below.

 

Angular PrimeNG Draggable Events:

  • onDragStart: This event accepts a callback that is triggered when the dragging begins.
  • onDrag: This event accepts a callback that is invoked on dragging.
  • onDragEnd: This event accepts a callback that is triggered when the dragging ends.

Angular PrimeNG Droppable Events:

  • onDrop: This event is fired when the draggable is dropped in the droppable area.
  • onDragEnter: This event is fired when the draggable enters the droppable area.
  • onDragLeave: This event is fired when the draggable leaves the droppable area.

Syntax:

// For Droppable
<div 
    pDroppable="..." 
    (event-name)="callback()"> 
    ...
</div>

Creating Angular Application and Installing the Module:

Step 1: Create an Angular application using the following command.

ng new appname

Step 2: After creating your project folder i.e. appname, move to it using the following command.

cd appname

Step 3: Finally, Install PrimeNG in your given directory.

npm install primeng --save
npm install primeicons --save

Project Structure: The project Structure will look like this after following the above steps:

Project Structure

Example 1: The below example illustrates the use of the draggable events and show a toast message in the top-right corner when any of the event fires.

  • app.component.html:

HTML




<h1 style="color:green">
    GeeksforGeeks
</h1>
<h3>
    Angular PrimeNG Drag 
    and Drop Drop Events
</h3>
  
<div class="grid">
    <div class="col-12 md:col-6">
        <p-table 
            [value]="available" 
            responsiveLayout="scroll">
            <ng-template pTemplate="header">
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                </tr>
            </ng-template>
            <ng-template pTemplate="body" let-person>
                <tr 
                    pDraggable="products" 
                    (onDragStart)="dragStart(person);" 
                    (onDrag)="drag()"
                    (onDragEnd)="dragEnd()">
                    <td>{{person.name}}</td>
                    <td>{{person.age}}</td>
                </tr>
            </ng-template>
        </p-table>
    </div>
  
    <div 
        class="col-12 md:col-6" 
        pDroppable="products" 
        (onDrop)="drop()" 
        responsiveLayout="scroll">
          
        <p-table [value]="selected">
            <ng-template pTemplate="header">
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                </tr>
            </ng-template>
            <ng-template pTemplate="body" let-person>
                <tr>
                    <td>{{person.name}}</td>
                    <td>{{person.age}}</td>
                </tr>
            </ng-template>
        </p-table>
    </div>
</div>
<p-toast [preventOpenDuplicates]="true"></p-toast>


  • app.component.ts:

Javascript




import { Component } from '@angular/core';
import { MessageService } from 'primeng/api';
  
interface Person {
    id: String;
    name: String,
    age: number,
}
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [MessageService]
})
export class AppComponent {
    constructor(private msg: MessageService){}
    available: Person[] = [];
    selected: Person[] = [];
  
    currentlyDragging: Person | null = null;
  
    ngOnInit() {
        this.available = [
            {
                id: "ASDF12",
                name: "Anshu",
                age: 19
            },
            {
                id: "KJHY45",
                name: "Shikhar",
                age: 22
            },
            {
                id: "LKIO34",
                name: "Jayant",
                age: 32
            },
            {
                id: "LPOI21",
                name: "Krishna",
                age: 23
            },
            {
                id: "VANI12",
                name: "Vanishka",
                age: 20
            }
        ];
    }
  
    // On Drag Start
    dragStart(person: Person) {
        this.currentlyDragging = person;
  
        // Show the toast message on the frontend
        this.msg.add({
            severity: "info",
            summary: "Drag Started",
            detail: "onDragStart Event"
        })
    }
  
    drag()
    {
        // Show the toast message on the frontend
        this.msg.add({
            severity: "success",
            summary: "Dragging...",
            detail: "onDrag Event"
        })
    }
  
    // On Drag End
    dragEnd() {
        this.currentlyDragging = null;
        // Show the toast message on the frontend
        this.msg.add({
            severity: "error",
            summary: "Drag End",
            detail: "onDragEnd Event"
        })
    }
  
    // On Drop of Item to droppable area
    drop() {
        if (this.currentlyDragging) {
            let currentlyDraggingIndex =
                this.findIndex(this.currentlyDragging);
            this.selected =
                [...this.selected, this.currentlyDragging];
            this.available =
                this.available.filter((val, i) => i !=
                    currentlyDraggingIndex);
            this.currentlyDragging = null;
        }
    }
  
    // Find the Index of a Person
    findIndex(person: Person) {
        let index = -1;
        for (let i = 0; i < this.available.length; i++) {
            if (person.id === this.available[i].id) {
                index = i;
                break;
            }
        }
        return index;
    }
}


  • app.module.ts:

Javascript




import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule }
    from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { TableModule } from 'primeng/table';
import { ToastModule } from 'primeng/toast';
import { DragDropModule } from 'primeng/dragdrop';
  
@NgModule({
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        HttpClientModule,
        FormsModule,
        TableModule,
        ToastModule,
        DragDropModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }


Output:

 

Example 2: In this example, we used the droppable events to notify the user about them using toast messages.

  • app.component.html:

HTML




<h1 style="color:green">
    GeeksforGeeks
</h1>
<h3>
    Angular PrimeNG Drag 
    and Drop Drop Events
</h3>
  
<div class="grid">
    <div class="col-12 md:col-6">
        <p-table 
            [value]="available" 
            responsiveLayout="scroll">
            <ng-template pTemplate="header">
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                </tr>
            </ng-template>
            <ng-template pTemplate="body" let-person>
                <tr 
                    pDraggable="products" 
                    (onDragStart)="dragStart(person);" 
                    (onDragEnd)="dragEnd()">
                    <td>{{person.name}}</td>
                    <td>{{person.age}}</td>
                </tr>
            </ng-template>
        </p-table>
    </div>
  
    <div 
        class="col-12 md:col-6" 
        pDroppable="products" 
        (onDrop)="drop()"
        (onDragEnter)="dragEnter()"
        (onDragLeave)="dragLeave()" 
        responsiveLayout="scroll">
          
        <p-table [value]="selected">
            <ng-template pTemplate="header">
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                </tr>
            </ng-template>
            <ng-template pTemplate="body" let-person>
                <tr>
                    <td>{{person.name}}</td>
                    <td>{{person.age}}</td>
                </tr>
            </ng-template>
        </p-table>
    </div>
</div>
<p-toast [preventOpenDuplicates]="true"></p-toast>


  • app.component.ts:

Javascript




import { Component } from '@angular/core';
import { MessageService } from 'primeng/api';
  
interface Person {
    id: String;
    name: String,
    age: number,
}
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [MessageService]
})
export class AppComponent {
    constructor(private msg: MessageService){}
    available: Person[] = [];
    selected: Person[] = [];
  
    currentlyDragging: Person | null = null;
  
    ngOnInit() {
        this.available = [
            {
                id: "ASDF12",
                name: "Anshu",
                age: 19
            },
            {
                id: "KJHY45",
                name: "Shikhar",
                age: 22
            },
            {
                id: "LKIO34",
                name: "Jayant",
                age: 32
            },
            {
                id: "LPOI21",
                name: "Krishna",
                age: 23
            },
            {
                id: "VANI12",
                name: "Vanishka",
                age: 20
            }
        ];
    }
  
    // On Drag Start
    dragStart(person: Person) {
        this.currentlyDragging = person;
    }
  
    dragEnter()
    {
        // Show the toast message on the frontend
        this.msg.add({
            severity: "info",
            summary: "Drag Enter",
            detail: "onDragEnter Event"
        })
    }
  
    dragLeave()
    {
        // Show the toast message on the frontend
        this.msg.add({
            severity: "error",
            summary: "Drag Leave",
            detail: "onDragLeave Event"
        })
    }
  
    // On Drag End
    dragEnd() {
        this.currentlyDragging = null;
    }
  
    // On Drop of Item to droppable area
    drop() {
        if (this.currentlyDragging) {
            let currentlyDraggingIndex =
                this.findIndex(this.currentlyDragging);
            this.selected =
                [...this.selected, this.currentlyDragging];
            this.available =
                this.available.filter((val, i) => i !=
                    currentlyDraggingIndex);
            this.currentlyDragging = null;
        }
  
  
        // Show the toast message on the frontend
        this.msg.add({
            severity: "success",
            summary: "Dropped",
            detail: "onDrop Event"
        })
    }
  
    // Find the Index of a Person
    findIndex(person: Person) {
        let index = -1;
        for (let i = 0; i < this.available.length; i++) {
            if (person.id === this.available[i].id) {
                index = i;
                break;
            }
        }
        return index;
    }
}


  • app.module.ts:

Javascript




import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule }
    from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { TableModule } from 'primeng/table';
import { ToastModule } from 'primeng/toast';
import { DragDropModule } from 'primeng/dragdrop';
  
@NgModule({
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        HttpClientModule,
        FormsModule,
        TableModule,
        ToastModule,
        DragDropModule
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }


Output:

 

Reference: http://primefaces.org/primeng/dragdrop



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads