Sortable in Angular using jQuery in application

In this article we discuss how to use jQuery in angular and then implement sortable the items in angular application.
First we need to import jQuery and jQuery-ui add in our application for that first we need to open the index.html file for add scripts and CSS.

<script
  src="https://code.jquery.com/jquery-1.12.4.js"
  integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU="
  crossorigin="anonymous"
></script>

<script
  src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"
  integrity="sha256-0YPKAwZP7Mp3ALMRVB2i8GXeEndvCq3eSl/WsAl1Ryk="
  crossorigin="anonymous"
></script>

<link
  rel="stylesheet"
  type="text/css"
  href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css"
/>

After addi9ng jQuery library in application when we use jQuery we need to declare variable display in below code.


declare var jQuery;

For sortable we need to use “AfterViewChecked” life cycle hook. because after view implement we need to add code for jQuery for trigger.
Display below code for “app.component.ts” file for implement sortable method in “ngAfterViewChecked”.


import { Component, OnInit, VERSION, AfterViewChecked } from '@angular/core';

declare var jQuery;
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewChecked, OnInit {
  viewcheck: boolean = false;
  displaysorting: any = [];
  itemslist: any = [];
  ngOnInit() {
    this.viewcheck = true;

    this.itemslist.push({ id: 1, name: 'Itemname 1' });
    this.itemslist.push({ id: 2, name: 'Itemname 2' });
    this.itemslist.push({ id: 3, name: 'Itemname 3' });
    this.itemslist.push({ id: 4, name: 'Itemname 4' });
    this.itemslist.push({ id: 5, name: 'Itemname 5' });
  }

  ngAfterViewChecked() {
    if (this.viewcheck === true) {
      jQuery('#sortable').sortable({
        placeholder: 'ui-state-heighlight',
        update: function (event, ui) {
          var str = [];
          jQuery('li.liststyle').each(function (index) {
            str[index] = jQuery(this).attr('id');
          });

          this.displaysorting = str;
          console.log(this.displaysorting);
        },
      });
    }
  }
}

In html file we used below code to display sortable items when we drag and drop it will sort id value accordingly.


<h2>Sortable Example</h2>

<ul id="sortable">
  <li id="{{ item.id }}" class="liststyle" *ngFor="let item of itemslist">
    {{ item.name }}
  </li>
</ul>

Output display in below video where item sort it change the index
Output

Spread the love