如何将 jquery 拖放转换为 angular?

How to convert jquery drag and drop to angular?

我正在 angular 项目中使用 jquery 和 jquery-ui 进行拖放功能,

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"));
        });
      }
    });
}
}

使用此代码一切正常,我可以拖放元素并获取相应位置索引值的变化。

但我需要将整个代码转换为打字稿,因为我不应该在项目中添加 jquery。我是 angular 和打字稿的初学者,因此请帮助我使用纯打字稿和基于 angular 的拖放操作,而不使用 jquery 和 jquery-ui.

我也尝试过使用两个 angular 库,例如 angular4-drag-dropng2-dragula 但是当我改变元素的位置时,索引值没有改变,所以我有使用 jquery 和上面的 jquery 主要用于获取索引,我需要用 angular 和打字稿来实现。

任何帮助我实现结果的解决方案都将更加可观。

使用Sortable js。这对 jQuery 没有任何依赖性。并在拖动时提供 oldIndex、newIndex 和其他属性。

Github(函数和属性): https://github.com/RubaXa/Sortable

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

示例:

// 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