Row Dragging in AG-Grid: Putting the Brakes On with External API Calls
Image by Electa - hkhazo.biz.id

Row Dragging in AG-Grid: Putting the Brakes On with External API Calls

Posted on

AG-Grid, the popular JavaScript data grid component, is a powerful tool for displaying and manipulating large datasets. One of its nifty features is row dragging, which allows users to reorder rows with ease. However, what if you want to stop row dragging in certain situations, like when a keyboard event is triggered? In this article, we’ll delve into the world of AG-Grid and explore how to halt row dragging using an external API call.

Understanding Row Dragging in AG-Grid

Before we dive into the solution, let’s take a step back and understand how row dragging works in AG-Grid. By default, AG-Grid allows row dragging when the `rowDragManaged` property is set to `true`. This enables users to grab a row and drag it to a new position, updating the underlying data accordingly.


const gridOptions = {
  // Enable row dragging
  rowDragManaged: true,
  // ... other grid options
};

The Problem: Stopping Row Dragging on External Events

Sometimes, you might want to stop row dragging based on external events, such as keyboard input or API calls. For instance, you might want to prevent row dragging when the user presses a specific key or when a remote validation fails. This is where things get tricky, as AG-Grid doesn’t provide a built-in way to cancel row dragging based on external events.

Using the `rowDragMove` Event

Luckily, AG-Grid provides the `rowDragMove` event, which is triggered whenever a row is dragged. We can use this event to intercept the row dragging process and cancel it if needed.


const gridOptions = {
  // ... other grid options
  onRowDragMove: params => {
    // Cancel row dragging if a certain condition is met
    if (/* some condition */) {
      params.cancel = true;
    }
  }
};

However, this approach has its limitations. The `rowDragMove` event is only triggered when the row is being dragged, which means we can’t cancel row dragging based on events that occur before the drag starts.

The Solution: Using an External API Call to Stop Row Dragging

To stop row dragging based on external events, we need to get creative and use a combination of AG-Grid’s API and JavaScript magic. The approach involves creating a custom row model, overriding the `onRowDragStart` method, and making an external API call to validate the drag operation.

Step 1: Create a Custom Row Model

Create a new JavaScript file and define a custom row model class that extends AG-Grid’s `RowModel` class.


import { RowModel } from '@ag-grid-community/core';

class CustomRowModel extends RowModel {
  constructor(...args) {
    super(...args);
  }
}

Step 2: Override the `onRowDragStart` Method

Override the `onRowDragStart` method in your custom row model to make an external API call and validate the drag operation. If the validation fails, cancel the row dragging operation.


class CustomRowModel extends RowModel {
  // ... other methods

  onRowDragStart(params) {
    // Make an external API call to validate the drag operation
    fetch('/api/validateDrag', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ /* validation data */ })
    })
      .then(response => response.json())
      .then(data => {
        if (!data.isValid) {
          // Cancel row dragging if validation fails
          params.event.preventDefault();
          params.event.stopPropagation();
        }
      })
      .catch(error => console.error(error));
  }
}

Step 3: Register the Custom Row Model

Register your custom row model with AG-Grid by creating a new instance and passing it to the `gridOptions` object.


const customRowModel = new CustomRowModel();

const gridOptions = {
  // ... other grid options
  rowModel: customRowModel
};

Putting it all Together

Now that we have our custom row model in place, let’s see how it all works together.


<div>
  <ag-grid-angular
    [gridOptions]="gridOptions"
    (rowDragMove)="onRowDragMove($event)"
  ></ag-grid-angular>
</div>

In this example, we’ve created a custom row model that makes an external API call to validate the drag operation. If the validation fails, the row dragging operation is canceled. We’ve also registered the custom row model with AG-Grid and hooked up the `rowDragMove` event to handle any additional logic.

Conclusion

Stopping row dragging in AG-Grid based on external events requires a bit of creativity and clever use of AG-Grid’s API. By creating a custom row model, overriding the `onRowDragStart` method, and making an external API call, we can seamlessly integrate external validation logic with AG-Grid’s row dragging feature.

Remember to adapt this solution to your specific use case and requirements. Whether you’re using AG-Grid with Angular, React, or plain JavaScript, the principles remain the same. Happy coding!

AG-Grid Version Supported
Enterprise v24.1.0 Yes
Community v24.1.0 Yes
Enterprise v23.2.0 Yes
Community v23.2.0 Yes
  1. AG-Grid Row Dragging: https://www.ag-grid.com/javascript-data-grid/row-dragging/
  2. AG-Grid Events: https://www.ag-grid.com/javascript-data-grid/events/

Frequently Asked Question

Get the scoop on Ag-grid row drag functionality and how to stop it in its tracks with an external API call!

Can I stop row dragging in ag-grid using an external API call?

Yes, you can! Ag-grid provides an API to cancel row dragging. You can use the `stopDragging()` method on the grid’s `rowDragger` component to stop the row dragging programmatically.

How do I access the rowDragger component in ag-grid?

You can access the rowDragger component through the grid’s API. Use the `.api.getRowDragger()` method to get an instance of the rowDragger component.

Can I stop row dragging on a specific keyboard event, like Escape?

Absolutely! You can listen to keyboard events on the grid and call the `stopDragging()` method when a specific key is pressed. For example, you can use the `onKeyDown` event to stop row dragging when the Escape key is pressed.

Is it possible to conditionally stop row dragging based on some external state?

Yes, it is! You can use a conditional statement to check the external state and then call the `stopDragging()` method if the condition is met. For example, you can check a flag variable and stop row dragging if it’s set to true.

Are there any performance considerations when stopping row dragging programmatically?

Good question! Since stopping row dragging programmatically can lead to unexpected behavior, it’s essential to ensure that you’re not interrupting the grid’s internal state. Avoid calling `stopDragging()` excessively or during critical grid operations to maintain optimal performance.

Leave a Reply

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