Dragging and dropping items from the Tree component into the DataTable

Is it possible to implement Drag and Drop functionality from a Tree component to a DataTable using PrimeNG?

I have tried implementing this feature, but my data is not draggable even though there are no errors after compilation. What could be the issue?

Here is an excerpt of my code:

drag.and.drop.ts

import { Component, OnInit } from '@angular/core';
import {Tree} from 'primeng/primeng';
import {DataTable} from 'primeng/primeng';
import {Column} from 'primeng/primeng';
import {Draggable,Droppable} from 'primeng/primeng';
import {ObjectsService} from "../app.tree/objects.service";
import {ClassObject} from "./class.object";

@Component({
selector: 'drag-drop',
template: `
    <p-growl [value]="msgs"></p-growl>
    <div class="row">
        <div class="col-md-6 col-xs-12" style="height: 600px">
            <div class="panel">
                <div class="panel-heading">
                    <label class="col-md-offset-5 col-xs-offset-5">All Objects</label>
                </div>
                <div class="panel-body">
                     <p-tree [value]="availableObjects" [style]="{'width':'470px','height':'530px'}"
                      selectionMode="single" [(selection)]="selectedFile" (onNodeSelect)="nodeSelect($event)"
                     pDraggable="classObjs" (onDragStart)="dragStart($event)" (onDragEnd)="dragEnd($event)"></p-tree>
                     Selected Node: {{selectedFile ? selectedFile.label : 'none'}}
                </div>
            </div>
        </div>
        <div class="col-md-6 col-xs-12" style="height: 600px;">
            <div class="panel">
                <div class="panel-heading">
                    <label class="col-md-offset-2 col-xs-offset-5">Objects related to Class</label>
                </div>
                <div class="panel-body" pDroppable="classObjs" (onDrop)="drop($event)"
                       [ngClass]="{'ui-state-highlight':draggedObject}">
                    <p-dataTable [value]="selectedObject">
                        <p-column field="name" header="Name"></p-column>
                        <p-column field="dBegin" header="Start Date"></p-column>
                        <p-column field="dEnd" header="End Date"></p-column>
                    </p-dataTable>
                    <div class="row" style="position: absolute; bottom: 0px;">
                        <p class="col-lg-1" style="height: 30px; width: 5px; border: 1px solid #000; background: #90E803"></p>
                        <label class="col-lg-7" style="font-size: 12px;"> - new entries</label>
                        <a title="Trash Can" type="button" class="col-lg-3 btn btn-lg" style="color: #000; float: right;">
                            <span class="glyphicon glyphicon-trash"></span></a>
                    </div>
                </div>
            </div>
        </div>
    </div>    
`,
directives: [Tree, DataTable, Column, Draggable, Droppable]
})
export class DragAndDrop implements OnInit {

availableObjects: ClassObject[];

selectedObjects: ClassObject[];

draggedObject: ClassObject;

constructor(private objectService: ObjectsService){}

ngOnInit() {
    this.selectedObjects = [];
    this.availableObjects = this.objectService.getObjects();
}

dragStart(event, classObj: ClassObject){
    this.draggedObject = event.node;
}

drop(event) {
    if(this.draggedObject) {
        this.selectedObjects.push(this.draggedObject);
        this.availableObjects.splice(this.findIndex(this.draggedObject), 1);
        this.draggedObject = null;
    }
}

dragEnd(event) {
    this.draggedObject = null;
}

findIndex(event) {
    let index = -1;
    for(let i = 0; i < this.availableObjects.length; i++) {
        if(event.node.label === this.availableObjects[i].label) {
            index = i;
            break;
        }
    }
    return index;
}
nodeSelect(event) {
    console.log(event.node);
}
}

object.service.ts

import { Injectable } from '@angular/core';
import {ClassObject} from "../app.drag.and.drop/class.object";

@Injectable()
export class ObjectsService {
getObjects():ClassObject[] {
    return [
        {
            "label": "1",
            "data": "Documents Folder",
            "expandedIcon": "fa-folder-open",
            "collapsedIcon": "fa-folder",
            "children": [
                {"label": "2", "icon": "fa-file-o", "data": "Expenses Document"},
                {
                    "label": "3",
                    "data": "Documents Folder",
                    "expandedIcon": "fa-folder-open",
                    "collapsedIcon": "fa-folder",
                    "children":[
                        {"label": "4", "icon": "fa-file-o", "data": "Expenses Document"},
                        {"label": "5", "icon": "fa-file-o", "data": "Expenses Document"},
                    ]
                },
            ]
        }
    ]
}
}

class.object.ts

import {TreeNode} from "primeng/primeng";

export interface ClassObject {
label?: string;
icon?: any;
expandedIcon?: any;
collapsedIcon?: any;
children?: TreeNode[];
leaf?: boolean;
data: any;
}

Answer №1

To enhance functionality, make sure to include draggableNodes="true" and droppableNodes="true".

<p-tree [value]="items" 
                    selectionMode="multiple" 
                    [(selection)]="selectedItems" 
                    (onItemSelect)="itemSelect($event)"
                    draggableNodes="true"
                    droppableNodes="true"
                    [contextMenu]="menu">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript along with the "this" parameter

Hi there, I'm encountering an issue with the code snippet below. It keeps throwing an error message that says "Property 'weatherData' does not exist on type 'XMLHttpRequest'." The purpose of this code is to display weather informat ...

Include a search query parameter in the URL by adding "?search=" to connect with a

In my react/typescript application, I have a client and server setup. The client requests data from the server and displays it using React. When making a request for data on the client side, this is how it's done: export const createApiClient = (): A ...

What are the best practices for adding OAuth security to my Angular front end, coupled with a Java back end?

My application uses Java11 springboot and Angular13 with the angular-oauth2-oidc library for open id connect authentication. While I am able to authenticate using OAuth2 in both the front and back end, I am facing issues with communication between them. T ...

The element Component is not recognized even after importing the module and applying the CUSTOM_ELEMENTS_SCHEMA schema

Recently, I integrated PinchZoom into my Angular 6 project as a node module called ngx-pinch-zoom. It's important to mention that my project is also based on Ionic 4. Within my app.module.ts file, I imported the PinchZoomModule and included CUSTOM_EL ...

What is the best approach to implement a recursive intersection while keeping refactoring in consideration?

I'm currently in the process of refactoring this code snippet to allow for the reuse of the same middleware logic on multiple pages in a type-safe manner. However, I am encountering difficulties when trying to write a typesafe recursive type that can ...

Using React and TailwindCSS to create interactive hover effects on elements within the Document Object Model

When hovering over a container, an icon appears. Currently, it is positioned relative to ensure it stays within the container. However, this positioning affects the vertical alignment of other items in the container. Using negative margins as a workaround ...

Reduced number of node modules

Which node modules are essential for a basic project? Is it possible to manually remove unnecessary ones or should I use npm install [a few essential requirements] I have a small website consisting of 5-10 pages where only one makes http requests to serv ...

Encountering an issue while attempting to create a fresh Angular project following a recent update of the

Recently, I decided to upgrade my Angular CLI version from 6.* to 8.* on my Mac. However, after completing the update, running the ng new app command resulted in an error. Here is the terminal output: ... CREATE timelines/e2e/src/app.po.ts (251 bytes) npm ...

What is the method for assigning a type to a value of uncertain type using type predicates?

I am encountering an issue with a type predicate function that is designed to assign a type to a JSON object interface Duck { canQuack: true } function isDuck(duck: unknown): duck is Duck { if (typeof duck !== "object" || ! duck) return false retur ...

Creating a tailored regular expression for validating email addresses

Up to this point, I have crafted a regex pattern as Pattern="^(?=.*[a-zA-Z].*)([a-zA-Z0-9._%+-]+@([a-zA-Z0-9-]+[a-zA-Z0-9-]+(\.([a-zA-Z0-9-]+[a-zA-Z0-9-])+)?){1,4})$" that meets the following criteria: Not all characters should be numbers, ...

Exploring the use of a customizable decorator in Typescript for improved typing

Currently, I am in the process of creating TypeScript typings for a JavaScript library. One specific requirement is to define an optional callable decorator: @model class User {} @model() class User {} @model('User') class User {} I attempted ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...

Error encountered with Angular web components utilizing custom elements

I am currently undertaking the task of developing a basic web component using Angular with Angular Elements. My progress so far includes: Installation of Elements using npm i @angular/elements --save Installation of npm i @webcomponents/custom-elements - ...

What prevents me from utilizing the Router object within a function set for the then() of a CRUD delete operation in my Angular service?

I'm currently tackling a challenge in my Angular project where I am attempting to utilize a Router class to navigate to a specific page from within a service class. Allow me to elaborate on my predicament. The service class in question looks like thi ...

Having trouble getting useFieldArray to work with Material UI Select component

I am currently working on implementing a dynamic Select field using Material UI and react-hook-form. While the useFieldArray works perfectly with TextField, I am facing issues when trying to use it with Select. What is not functioning properly: The defau ...

What is the best way to extract values from a specific table column and store them in an array using Angular?

I have a section of code containing a table in my component: expect-next-month.component.html <table id="users"> <tr> <th>Number of month</th> <th>Total checking e ...

Ways to transform a JSON format into a collection of arrays?

I received a json response that looks like this: [ { "Value":"80,120" }, { "value2":"117,120" }, { "value3":"105,111" }, { "value4":"40,77" }, { "value5":"27,44" } ] Is there a way to transform this json structure int ...

Issue with Angular form not displaying data from bound object

Currently, I am in the process of designing an angular form that consists of 2 input fields. The objective is to submit these values to a function for further processing. I have double-checked to ensure that both FormsModule and NgForm have been imported ...

Can we dynamically assign types to portions of a TypeScript interface?

I'm looking for a way to extend a TypeScript object with a specific type. Here's an example scenario: interface BaseInterface<T> { staticA: string; staticB: number; dynamicA: T; } BaseInterface<SomeOtherInterfaceOrType> When u ...

What are the steps to incorporate web components into a Vue project with Typescript?

I am currently facing an issue with integrating a web component into my Vue project. Despite seeing the element in the DOM, it appears as an empty tag instead of the button it should be. The first error I encountered was the absence of a declared module. ...