Converting jQuery drag and drop functionality to Angular: A step-by-step guide

I have implemented drag and drop functionality using jquery and jquery-ui within an angular project. Below is the code structure:

Index.html,

<!doctype html>
<html lang="en">
<head>
    <link href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

  <meta charset="utf-8">
  <title>Drag</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

app.component.html:

<ul id="people">
  <li *ngFor="let person of people; let i = index">
    <div class="draggable" id={{i}}>
      <p> <b> {{ person.name }} </b> Index => {{i}}</p>
    </div>
    <br><br>
  </li>
</ul>

app.component.ts:

import { Component } from '@angular/core';
declare var jquery:any;
declare var $ :any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'My application';

  people: any[] = [
    {
      "name": "Person 1"
    },
    {
      "name": "Person 2"
    },
    {
      "name": "Person 3"
    },
    {
      "name": "Person 4"
    },
    {
      "name": "Person 5"
    }
  ];

  ngOnInit(): void {
    $("#people").sortable({
      update: function(e, ui) {
        $("#people .draggable").each(function(i, element) {
          $(element).attr("id", $(element).index("#people .draggable"));
          $(element).text($(element).text().split("Index")[0] + " " + "Index: " + " => " + $(element).attr("id"));
        });
      }
    });
}
}

While this implementation works well, I am looking to convert the code to typescript without the use of jquery and jquery-ui. I am new to angular and typescript, so I would appreciate any guidance on achieving drag and drop functionality in pure typescript and angular, avoiding jquery altogether.

I have explored libraries like angular4-drag-drop and ng2-dragula, but encountered issues with updating index values when reordering elements. Hence, I relied on jquery. However, I am seeking a solution that enables me to achieve the same result using angular and typescript exclusively.

I welcome any suggestions or solutions to help me accomplish this task effectively.

Answer №1

Utilize Sortable js library for drag and drop functionality without jQuery dependencies, providing access to oldIndex, newIndex, and other properties during the drag operation.

Explore Functions and Properties on Github: https://github.com/RubaXa/Sortable

Install via NPM: : https://www.npmjs.com/package/sortablejs

Check out some examples below:

// Element dragging started
onStart: function (/**Event*/evt) {
    evt.oldIndex;  // element index within parent
},

// Element dragging ended
onEnd: function (/**Event*/evt) {
    var itemEl = evt.item;  // dragged HTMLElement
    evt.to;    // target list
    evt.from;  // previous list
    evt.oldIndex;  // element's old index within old parent
    evt.newIndex;  // element's new index within new parent
},

Example 1

Example 2

Example 3

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

Automatically adjusting the locale settings upon importing the data

Is there a way to create a dropdown menu of languages where clicking on one language will change the date format on the page to match that country's format? In my React app, I am using moment.js to achieve this. My plan is to call moment.locale( lang ...

Handling errors in Angular and rxjs when encountering undefined returns in find operations

I am currently faced with the challenge of catching an error when the variable selectionId, derived from my route, is null or contains an invalid value. My code structure has a mechanism in place to handle errors when the category variable is undefined, bu ...

What is the best way to transform a string representation of data into an array and then showcase it in

After importing CSV data and converting it into the variable stringData, I am facing an issue when trying to display this data in a React table. Although I have attempted to use the map function to separate the headers and map to <th>, displaying t ...

Tips on retrieving an item using jQuery's select2 plugin

How can I retrieve the value (flight_no) from the processResults function in order to populate the airline name with the respective flight number when selected? I've attempted to access the (flight_no) within the processResults function, but I'm ...

Toggle Canvas Visibility with Radio Button

As I immerse myself in learning Javascript and Canvas, the plethora of resources available has left me feeling a bit overwhelmed. Currently, I am working on a dress customization project using Canvas. // Here is a snippet of my HTML code <input type=" ...

Exclude basic authentication for a specific route

Using node, express and connect for a simple app with basic HTTP auth implemented. The code snippet below shows part of the implementation: var express = require('express'), connect = require('connect'); app.configure = function(){ ...

What is the best way to implement an AJAX request to update the page without having to refresh it?

My to-do app currently reloads the page when I click on "Add" in order for the changes to take effect and display the items. However, I want to implement AJAX requests so that the page does not need to refresh. Can anyone guide me on how to achieve this? ...

Attempting to use Model.remove() is proving to be completely ineffective

Currently, I am utilizing expressjs (version 3.10.10), mongoose (version 3.10.10), and mLab for my project. Below is the code snippet: app.get("/deleteDevice/:query", function(req, res) { var query = req.params.query; query = JSON.stringify(quer ...

Guide to configuring browserify

After installing the modules (browserify, react, reactify), I attempted to process a JSX file using browserify. var React = require("react"); var App = React.createClass({ render: function () { return <h1>111</h1> } }); React ...

Disappearances of sliding jQuery divs

I am currently working on a website using jQuery, and I have implemented a slide in and out div to display share buttons. The issue I am facing is that the code works perfectly on the first page, but on every other page, the div slides out momentarily and ...

Issue with applying Angular animation to child element

Here I have set up two different animations. animations: [ trigger('fadeIn', [ transition('void => *', [ style({opacity: 0}), animate(500), ]), ]), trigger('fallIn',[ transition ...

Organize divs based on their attributes

Using inspiration from this SO post, my goal is to group divs based on their "message-id" attribute. The idea is to wrap all divs with the same "message-id" in a div with the class name "group". <div class="message" message-id="1"> ...

Experience the quirk of using Angular's mat-button-toggle-group with the multiple attribute, and uncover the

I'm experiencing a strange issue with the mat-button-toggle. Here is the code snippet: <mat-button-toggle-group formControlName="fcCWShowForms" multiple="true"> <mat-button-toggle value="HE" (change)="this.showHe=!this.showHe"> Button ...

Oops! There was an issue trying to solve the command "/bin/bash -ol pipefail -c npm run build" while deploying a Next.js app on Railway. Unfortunately, it did not complete successfully and returned an exit code of

[stage-0 8/10] RUN --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-next/cache,target=/app/.next/cache --mount=type=cache,id=s/8a557944-4c41-4e06-8de9-06bfcc5e8aaf-node_modules/cache,target=/app/node_modules/.cache npm run build: 17.62 17.62 ...

The specific module 'franc' does not have the export named 'default' as requested

Every time I attempt to use the franc package, I encounter the following error message: "The requested module 'franc' does not provide an export named 'default'." Unfortunately, I am unsure of what this means, despite trying to resolve ...

Creating a JavaScript function that increments or decrements a variable based on keyboard input is a useful feature

My goal is to have a count start at 100 and then either count up or down by 1 when a specific keyboard button is pressed. Currently, I am using the keys 8 and 2 on the keypad, which represent ascii numbers 104 and 98. So far, the code I have only allows f ...

Error handling proves futile as Ajax upload continues to fail

Utilizing a frontend jQuery AJAX script, I am able to successfully transfer images onto a PHP backend script hosted by a Slim framework app. However, there is one specific image (attached) that is causing an issue. When the backend attempts to send back a ...

What is preventing you from utilizing TypeScript's abstract classes for generating React factories, especially when regular classes seem to function properly?

Here is an example showcasing the behavior of TypeScript code using React with abstract classes: import * as React from "react"; class MyComponent<P> extends React.Component<P, any> { static getFactory() { return React.createFacto ...

The AJAX request successfully retrieves data, but the page where it is displayed remains empty

I have come across similar questions to mine, but I have not been successful in implementing their solutions. The issue I am facing involves an AJAX call that is functioning correctly in terms of receiving a response. However, instead of processing the re ...

Using TypeScript - Implementing a generic constraint to allow passing a Zod schema result as an argument to a function

I'm in the process of creating a custom controller function to streamline my application. The repetitive task of wrapping try-catch, parsing a zod schema, and merging the request zod schema into a single object is present in all handler functions. The ...