Angular: How to Drag & Drop with FormArray

Angular Drag and Drop with FormArray Tutorial
Dhara Tank
26-Aug-2021
Reading Time: 3 minutes

In this tutorial article we’ll learn how we can we drag and drop with FormArray in Angular 11.

Prerequisites:

  1. Prior knowledge of TypeScript
  2. Prior knowledge of JavaScript
  3. Visual studio code
  4. A development machine with Node 8.9+ & NPM 5.5.1+ installed

How to Drag and Drop with FormArray in Angular: Step by Step Tutorial

Step 1: Installing Angular CLI

First step, where we’ll have to install latest version of Angular CLI

$ npm install -g @angular/cli

Step 2: Creating your Angular 11 Project

In this second step, we will use Angular CLI to start our Angular Project

Go to CMD or Terminal and use this command:

$ ng new sample-demo

This CLI will ask you “whether you would like to add Angular routing” Say Yes.
It will ask “which stylesheet format you would like to use”. Choose CSS.

Now your project is ready Angular CLI will generate required files and folders along with NPM packages and routing too.

Now open your project in Visual studio code and go to your root folder and run the local development server using below command:

$ npm start

Now run localhost:4200/ in your browser

Step 3: Create Interface / Class

Step 3 Image 1 Angular: How to Drag & Drop with FormArray
export interface ICustomerDocument {
    customerName: string;
    documents: IDocument[];
}

export interface IDocument {
    docName: string;
    orderNumber: number;
}

Step 4: Set Model in page

Import Interface into sample.ts

import { ICustomerDocument, IDocument } from '../app.interface';

Declare Model in

model: ICustomerDocument = <ICustomerDocument>{};

Step 5: Set Formgroup / fromarray

Set ReactiveModule / FormModule in AppModule

Step5 Image1 Angular: How to Drag & Drop with FormArray
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
export class SampleComponent implements OnInit {
  custDocForm: FormGroup;
 docListForm: FormArray;
  docList: IDocument[] = [];
  isSubmitted: boolean = false;

  model: ICustomerDocument = <ICustomerDocument>{};

Set Form in HTML

Step5 Image2 Angular: How to Drag & Drop with FormArray

After set HTML , form will be looks like

Step5 Image3 Angular: How to Drag & Drop with FormArray

Step 6: Initialize form

initializeDocumentDetailForm() {
    this.custDocForm = this.formBuilder.group({
      customerName: ['', Validators.required],
      documents: new FormArray([this.formBuilder.group({
        docName: ["Document 1", Validators.required],
        orderNumber: [1, Validators.required],
      })
      ]),
    });

    this.docListForm = this.custDocForm.get('documents') as FormArray;
  }

  get custForm() { return this.custDocForm.controls; }
  get documentForm() { return this.custForm.documents as FormArray; }
-ngOnInit(): void {
-    this.initializeDocumentDetailForm();

Step 7: Set Jquery UI in index.ts

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Step 8: set drag n drop method (setDocusmentOrder) in onInit

ngOnInit(): void {
    this.initializeDocumentDetailForm();
    this.setDocumentOrder();
  }
SetDocuementIndex() {

    let childDiv = Array.from($("#sortable").children());
    let copyDocList = [];
    let _docList = this.GetDocumentList();
    for (var i = 0; i < childDiv.length; i++) {
      let element = childDiv[i];
      let _orderId = element["attributes"]["data-id"].value;
      let copyDoc = <IDocument>{};
      copyDoc = Object.assign({}, _docList.filter(f => f.orderNumber == _orderId)[0]);
      copyDoc.orderNumber = i + 1;
      copyDocList.push(copyDoc);
    }
    setTimeout(() => {
      this.docList = copyDocList;
      let _len = this.documentForm.controls.length;
      for (var idx = _len; idx > 0; idx--) {
        this.documentForm.removeAt(idx - 1);
      }
      for (var idx = 0; idx < this.docList.length; idx++) {
        let element = this.docList[idx];
        this.docListForm.controls.push(
          this.formBuilder.group({
            docName: [element.docName, Validators.required],
            orderNumber: [element.orderNumber, Validators.required],
          })
        );
      }
      this.cd.detectChanges();
    }, 200);
  }
GetDocumentList() {
    let _docList = this.custForm.documents.value;
    if (_docList == null || _docList == undefined || _docList.length == 0) {
      if (this.docList != null && this.docList != undefined && this.docList.length > 0) {
        _docList = this.docList;
      }
    }
    else {
      this.docList = _docList;
    }
    return _docList;
  }

Output

That’s it. Over To You!

Looking for a Sample Source Code? Here you go: GITHUB.

That’s it for now. Today you have learned how to drag & drop with FormArray in Angular. Happy Coding…

At last, If you’re dealing with large-scale applications or enterprise software, it is beneficial to take experts’ help. If you’re looking for an expert helping hand, contact Samarpan Infotech and hire Angular developers with having minimum of 5+ years of experience working on enterprise software.

Explore more:

  1. What is Linting in Angular? Understand it with example
  2. Angular: N Level FormArray With Reactive Form Validation