How to Implement Drag and Drop on a Table List with Pagination in Angular?
Image by Litton - hkhazo.biz.id

How to Implement Drag and Drop on a Table List with Pagination in Angular?

Posted on

Hey there, fellow Angular enthusiasts! Are you tired of dealing with boring, static tables that lack interactivity? Do you want to take your Angular application to the next level by adding a feature that will make your users go “Wow!”? Look no further! In this comprehensive guide, we’ll show you how to implement drag and drop functionality on a table list with pagination in Angular.

Why Drag and Drop Matters

Drag and drop is an intuitive way to interact with digital objects, making it an essential feature in modern web applications. By allowing users to reorder items in a table list, you can improve their experience and increase engagement. Moreover, with pagination, you can efficiently handle large datasets and provide a seamless user experience.

Prerequisites

Before we dive into the implementation, make sure you have the following installed:

  • Angular 10 or later (we’ll be using Angular 12 in this example)
  • TypeScript 4.1 or later
  • Node.js 14 or later
  • A code editor or IDE of your choice (we recommend Visual Studio Code)

Step 1: Create a New Angular Project

Create a new Angular project using the Angular CLI:

ng new drag-and-drop-pagination-app

Step 2: Generate Components and Services

Generate the necessary components and services:

ng generate component table-list
ng generate component pagination
ng generate service data

Step 3: Create a Data Service

In the data.service.ts file, add the following code:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  private data: any[] = [];

  constructor() { }

  getData(): any[] {
    return this.data;
  }

  addData(item: any) {
    this.data.push(item);
  }

  removeData(item: any) {
    this.data = this.data.filter(i => i !== item);
  }

}

Step 4: Implement Pagination

In the pagination.component.ts file, add the following code:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-pagination',
  template: `
    <ul>
      <li *ngFor="let page of pages">
        <a (click)="changePage(page)">{{ page }}</a>
      </li>
    </ul>
  `
})
export class PaginationComponent implements OnInit {

  pages: number[] = [];
  currentPage: number = 1;

  constructor(private dataService: DataService) { }

  ngOnInit(): void {
    this.calculatePages();
  }

  calculatePages() {
    const dataLength = this.dataService.getData().length;
    const pageSize = 10;
    this.pages = Array(Math.ceil(dataLength / pageSize)).fill(0).map((x, i) => i + 1);
  }

  changePage(page: number) {
    this.currentPage = page;
  }

}

Step 5: Implement Table List with Drag and Drop

In the table-list.component.ts file, add the following code:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-table-list',
  template: `
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody cdkDropList [cdkDropListData]="data" [cdkDropListOrientation]="'vertical'">
        <tr *ngFor="let item of data; let i = index" cdkDrag>
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
        </tr>
      </tbody>
    </table>
  `,
  providers: [{ provide: CdkDropList, useExisting: CdkDropList }]
})
export class TableListComponent implements OnInit {

  data: any[] = [];

  constructor(private dataService: DataService) { }

  ngOnInit(): void {
    this.data = this.dataService.getData();
  }

  drop(event: CdkDragDrop<any[]>) {
    moveItemInArray(this.data, event.previousIndex, event.currentIndex);
  }

}

Step 6: Integrate Pagination with Table List

In the table-list.component.ts file, update the ngOnInit() method:

ngOnInit(): void {
  this.dataService.getData().subscribe(data => {
    this.data = data.slice((this.pagination.currentPage - 1) * 10, this.pagination.currentPage * 10);
  });
}

In the pagination.component.ts file, update the changePage() method:

changePage(page: number) {
  this.currentPage = page;
  this.tableListComponent.data = this.dataService.getData().slice((page - 1) * 10, page * 10);
}

Step 7: Add Drag and Drop Icon

In the table-list.component.html file, add the following code:

<td><i class="fas fa-arrows-alt-v"></i></td>

Step 8: Style the Component

In the table-list.component.css file, add the following code:

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th:first-child {
  width: 20px;
}

.cdk-drop-list {
  min-height: 50px;
  padding: 10px;
  border: 1px solid #ccc;
}

.cdk-drag {
  cursor: move;
}

.cdk-drag-placeholder {
  opacity: 0;
}

.cdk-drop-list.cdk-drop-list-vertical {
  flex-direction: column;
}

Conclusion

And that’s it! You now have a fully functional drag and drop table list with pagination in Angular. This implementation provides a seamless user experience, allowing users to reorder items in a table list with ease. With pagination, you can efficiently handle large datasets and reduce the load on your application.

Remember to test your application thoroughly to ensure that the drag and drop functionality works as expected. You can also customize the appearance and behavior of the drag and drop feature to suit your application’s needs.

Bonus: Adding More Features

Want to take your application to the next level? Consider adding the following features:

  • Implementing item deletion
  • Adding a search bar for filtering data
  • Creating a custom drag and drop handle
  • Integrating with a backend API for data persistence

With these additional features, you can create a robust and scalable application that meets the needs of your users.

Final Thoughts

In this comprehensive guide, we’ve shown you how to implement drag and drop functionality on a table list with pagination in Angular. By following these steps, you can create a intuitive and user-friendly application that provides a seamless experience for your users.

Remember to experiment and customize the implementation to suit your application’s needs. Happy coding!

Keyword Frequency
Drag and Drop 10
Pagination 5
Angular 8
Table List 6

Frequently Asked Question

Get ready to drag and drop your way to a more interactive table list with pagination in Angular! Here are the top 5 questions and answers to help you implement this feature like a pro:

What is the best approach to implement drag and drop on a table list with pagination in Angular?

The best approach is to use a combination of Angular’s built-in directives and a library like Angular Material or ng-draggable. This will allow you to handle the drag and drop events and update the table data accordingly. Don’t forget to handle the pagination logic to ensure that the dragged item is moved to the correct page!

How do I handle the drag and drop events in my Angular application?

You can use Angular’s `(dragstart)` and `(dragend)` events to capture the drag and drop events. Then, update the table data by moving the item to its new position and adjusting the pagination accordingly. Don’t forget to handle the case where the user drags an item to a different page!

How do I ensure that the dragged item is moved to the correct page in the paginated table?

When the user drags an item, store the item’s current page and position. When the user drops the item, calculate the new page and position based on the drop location. Then, update the table data and pagination accordingly. You may need to use some math magic to get it right!

Can I use a third-party library to simplify the drag and drop implementation?

Yes, you can use libraries like Angular Material, ng-draggable, or dragula to simplify the drag and drop implementation. These libraries provide built-in directives and services that can handle the drag and drop events for you. Just make sure to follow their documentation and adapt their solutions to your specific use case!

How do I optimize the performance of my drag and drop table list with pagination?

To optimize performance, use Angular’s change detection strategy to minimize unnecessary DOM updates. Also, consider using virtual scrolling or lazy loading to reduce the number of items rendered in the table. Finally, use caching or memoization to reduce the number of calculations required for the drag and drop logic!

Leave a Reply

Your email address will not be published. Required fields are marked *