Looking to effortlessly move and arrange items with ng2-drag-drop in Angular 2?

I have encountered a problem with the ng2-drag-drop library. I am trying to drag and drop items from one div to another, and then freely move the dropped item within the droppable area.

One issue I'm facing is that when I drop my draggable item in the corners of the droppable area, the divs shrink.

Another issue is related to dragging the dropped items. I applied the draggable attribute to them, but it ends up creating duplicate copies instead of allowing me to freely drag the original item without duplication. Is there a way to control this behavior?

    <div class="container">
    <div class="row">
    <div class="col-xs-12">
      <nav class="breadcrumb">
        <a class="breadcrumb-item" href="#">Home &gt;</a>
        <a class="breadcrumb-item" href="#">Library &gt;</a>
        <a class="breadcrumb-item" href="#">Data &gt;</a>
        <span class="breadcrumb-item active">Bootstrap</span>
      </nav>
    </div>
  </div>
</div>

    <div class="container">
    <div class="row">
    <div class="col-xs-12 col-sm-9">
      <div class="row drag-drop-area">
        <div class="col-xs-12 col-sm-4 col-lg-3 bg-white left-sidebar">
          <button class="btn room-obj-btn">Room Objects <span 
    class="glyphicon glyphicon-arrow-right pull-right"></span></button>
          <div class="category">Type</div>
          <div class="drag-drop">(Drag and drop to add item)</div>
          <div class="row">
            <div class="col-xs-6 col-sm-12 col-md-6 surgery-objects-block" 
    draggable [dragData]="'Item 1'">
              <div class="surgery-elements">item 1</div>
            </div>
          </div>
        </div>
        
        <div class="droppable-area col-xs-12 col-sm-8 col-lg-9 drop-area" 
    droppable (onDrop)="onItemDrop($event,evt)" style="min-height: 883px">
          <div class="abc" *ngFor="let item of droppedItems" 
    style="position: absolute" [style.top]="item.nativeEvent.layerY + 'px'" 
    [style.left]="item.nativeEvent.layerX +'px'"> <div class="surgery-
    elements" draggable >Item 1</div></div>
        </div>
      </div>
    </div>
  </div>
</div>

You can view a Plunker demo of my implementation by clicking on the link below:

http://plnkr.co/edit/UtgrchNDpiq6CAssilyR?p=preview

Answer №1

Resolution for Problem 2

complete-demo-component.html

Include dragData and dragScope attributes to your draggable Div.

Add the following indexing code:

*ngFor="let item of droppedItems; let i = index;"

Modify the draggable div as follows:

<div class="surgery-elements" draggable [dragScope]="'alreadyDropped'" [dragData]="i" >Item 1</div>

<div class="col-xs-12 col-sm-9">
  <div class="row drag-drop-area">

    <div class="col-xs-12 col-sm-4 col-lg-3 bg-white left-sidebar">

      <button class="btn room-obj-btn">Room Objects <span class="glyphicon glyphicon-arrow-right pull-right"></span></button>
      <div class="category">Type</div>
      <div class="drag-drop">(Drag and drop to add item)</div>
      <div class="row">
        <div class="col-xs-6 col-sm-12 col-md-6 surgery-objects-block" draggable [dragScope]="'leftItem'" [dragData]="{'data':'Item 1', isFirstTimeDrop:'true'}">
          <div class="surgery-elements">item 1</div>
        </div>
      </div>
    </div>
    <div class="droppable-area col-xs-12 col-sm-8 col-lg-9 drop-area" droppable [dropScope]="['leftItem', 'alreadyDropped']" (onDrop)="onItemDrop($event,evt)" style="min-height: 883px">
      <div class="abc" *ngFor="let item of droppedItems; let i = index;" style="position: absolute" [style.top]="item.nativeEvent.layerY + 'px'" [style.left]="item.nativeEvent.layerX +'px'"> <div class="surgery-elements" draggable [dragScope]="'alreadyDropped'" [dragData]="i" >Item 1</div></div>
    </div>
  </div>
</div>

complete-demo-component.ts

onItemDrop(e: any,evt) {
    // Obtain the dropped data here
    alert(JSON.stringify(e));
    if(e.dragData.isFirstTimeDrop != undefined) {
      this.droppedItems.push(e); 
    } else {
      this.droppedItems[e.dragData] = e;
    }
}

Plnkr Link http://plnkr.co/edit/pMRjGfHncUDf8PtVQIoT?p=preview

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

Problems with JQuery UI buttonset behavior

As I develop a UI application utilizing JQuery UI components, I encounter an issue with aligning radio buttons within the interface. While using JQuery buttonset in isolation functions correctly, integrating it with other UI elements causes misalignment: ...

Tips for transitioning this JavaScript code into jQuery syntax

Below is my JavaScript code: javascript: function executeCode() { var d = document; try { if (!d.body) throw (0); window.location = 'http://www.example.com/code?u=' + encodeURIComponent(d.location.href); } catch (e) { ...

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...

How can I apply a border to individual table cells in HTML without affecting the entire table?

Struggling to apply a border on table cells, especially when using rowspan. Desiring a table layout with 4 cells - one large cell on the left and three smaller cells on the right side of it. Below is the code snippet I attempted: jsfiddle[dot]net/1fv4dz ...

Preventing the build-up of opacity animations in jQuery: Tips and tricks

-I have two division tags in my code. <div id="div1">Hover over me to show Div2</div> <div id="div2">Div2</div> -I used CSS to set the opacity of div2 to 0. -My goal is for div2's opacity to change from 0 to 1 when hovered o ...

Ways to set a background image for two separate components in Angular

Trying to figure out how to integrate this design: The challenge lies in having a background image that spans across the navbar and the content below it. Currently, the code separates the navbar component from the content component, making it tricky to ac ...

What is the best method for identifying the destination of my data submission in an HTML form?

I am currently facing an issue with a website that has an input form. I am struggling to identify where the form posts its data to. There must be some PHP code handling the form, whether it's using JSON or direct post. Is there a way to find this in ...

Error message: Module 'firebase/app' not found in angular framework

I am currently working through a Google codelab, which can be found at this link: Check out the codelab here However, when I attempt to build the project using 'ng build --prod', I encounter the following error: ERROR in node_modules/@angular ...

Tips for including HTML tags in strings without causing issues with nested tags

I am struggling with a string that contains both text and HTML tags, specifically <a href=""></a> tags. My goal is to apply the "i" tag around the text outside of the "a" tags without creating nested tags like: <i><a href=""></a ...

When I attempt to map imports in Typescript, an error occurs, stating, "Element implicitly has an 'any' type because the expression of type 'string' is being indexed into type 'typeof import'."

(parameter) key: string An issue arises where the expression of type 'string' cannot be used to index type 'typeof import("d:/Projects/Front/attendance-checker2/src/redux/modules/sagas")', leading to an implicit 'any&a ...

Together, we have a shared Yarn JS directory for both the client and server components,

The scenario: both the client and server share a folder named shared when we make changes to the shared folder in our development process, we need the corresponding references to update in both the client and server the server seems to w ...

Incorporating the <sub> element while maintaining the line height

I am facing a challenge with formatting text that includes subscripts and superscripts tags. For example: <div>hello <sub>world</sub>, how are you? Translated as logical aggregates or associative compounds, these characters have been int ...

Getting JSON with duplicate keys in JavaScript can be achieved by parsing the data using a custom function

I am attempting to retrieve JSON from a URL, but I have encountered an issue where the response object is removing duplicate keys. Is there a way to fetch the JSON without eliminating these duplicates? Below is my JavaScript code: $('document'). ...

Issues arise when attempting to smoothly scroll to an anchor point in a webpage

While working on my website, I have encountered a challenge. The issue arises when dealing with multiple div items. Upon scrolling slightly, the entire page focuses on the div with a height of 100vh, which works perfectly fine. However, my attempts to ...

Styling with floated divs in CSS

I'm facing a rather unique issue while working on creating a menu for a web page. The main challenge lies in ensuring that the parent element containing floated child divs adjusts its height dynamically, especially when changes are made to the padding ...

Amusing antics observed when hovering over a div in Firefox

Issue resolved, many thanks to all Here is the dilemma I am dealing with something like this <a href='http://google.com' class="buy_now" > <div class='yada yada' > Go </div> </a> buy_now changes backgro ...

Optimal method for efficiently caching data when toggling between list view and detail view within Angular 12

In my Angular App, I have implemented two components - a list view and a details view. Users can switch between these components, both of which utilize multiple async pipes. To minimize the number of http requests to the backend, I decided to cache data u ...

Leveraging the Angular Material 2 table component to showcase data fetched from the backend system according to the user's present location

This question is similar to another one about how to get the current location in Typescript and pass it to a backend, which was answered by libertyernie. However, this time I need help with integrating the current location into an Angular Material 2 table ...

Asynchronously parsing CSV files in NodeJs using the `await` keyword within the `on('data')`

I have a specific code snippet that is designed to read lines from a .csv file one by one and then store each processed row into a database const csv = require('csv-parse') const errors = [] csv.parse(content, {}) .on('data', async ...

What is the method to combine multiple style values in vue.js?

Is there a way to create a div with a box shadow where the values can be changed using a slider? I am having trouble using more than one value stored in a data variable. Any suggestions on how to achieve this? <div :style="{ borderRadius: x_axis y_ ...