Row Dragging in Blazor Grid

    La función de arrastre de filas Ignite UI for Blazor en Blazor cuadrícula es fácilmente configurable y se utiliza para reorganizar filas dentro de la cuadrícula arrastrándolas y soltándolas a una nueva posición con el mouse. Se inicializa en el componente raíz IgbGrid y se puede configurar a través de la RowDraggable entrada.

    Blazor Grid Row Drag Example

    EXAMPLE
    MODULES
    DATA
    RAZOR
    JS
    CSS

    Like this sample? Get access to our complete Ignite UI for Blazor toolkit and start building your own apps in minutes. Download it for free.

    Configuration

    Para habilitar el arrastre de filas para su IgbGrid, todo lo que necesita hacer es configurar RowDraggable de la cuadrícula en verdadero. Una vez que esto esté habilitado, se mostrará un controlador de arrastre de fila en cada fila. Este controlador se puede utilizar para iniciar el arrastre de filas. Al hacer clic en el controlador de arrastre y mover el cursor mientras se mantiene presionado el botón, se activará el evento RowDragStart de la cuadrícula. Si suelta el clic en cualquier momento, se activará el evento RowDragEnd.

    <IgbGrid RowDraggable="true">
    </IgbGrid>
    razor

    Templating the Drag Icon

    Se puede crear una plantilla para el icono del controlador de arrastre utilizando DragIndicatorIconTemplate de la cuadrícula. En el ejemplo que estamos creando, cambiemos el ícono predeterminado (drag_indicator) a drag_handle.

    Para hacerlo, podemos usar DragIndicatorIcon para pasar una plantilla dentro del cuerpo de IgbGrid:

    <IgbGrid Data="CustomersData" PrimaryKey="ID" RowDraggable="true" DragIndicatorIconTemplate="dragIndicatorIconTemplate" @ref="grid">
    </IgbGrid>
    
    private RenderFragment<IgbGridEmptyTemplateContext> dragIndicatorIconTemplate = (context) =>
    {
        return @<div>
            <IgbIcon IconName="drag_handle" Collection="material"></IgbIcon>
        </div>;
    };
    razor

    Application Demo

    Row Reordering Demo

    Con la ayuda de los eventos de arrastre de filas de la cuadrícula, puede crear una cuadrícula que le permita reordenar las filas arrastrándolas.

    <IgbGrid Data="CustomersData" PrimaryKey="ID" RowDraggable="true" RowDragEndScript="WebGridReorderRowHandler"></IgbGrid>
    
    // In JavaScript
    igRegisterScript("WebGridReorderRowHandler", (args) => {
        const ghostElement = args.detail.dragDirective.ghostElement;
        const dragElementPos = ghostElement.getBoundingClientRect();
        const grid = document.getElementsByTagName("igc-grid")[0];
        const rows = Array.prototype.slice.call(document.getElementsByTagName("igx-grid-row"));
        const currRowIndex = this.getCurrentRowIndex(rows,
        { x: dragElementPos.x, y: dragElementPos.y });
        if (currRowIndex === -1) { return; }
        // remove the row that was dragged and place it onto its new location
        grid.deleteRow(args.detail.dragData.key);
        grid.data.splice(currRowIndex, 0, args.detail.dragData.data);
    }, false);
    
    function getCurrentRowIndex(rowList, cursorPosition) {
        for (const row of rowList) {
            const rowRect = row.getBoundingClientRect();
            if (cursorPosition.y > rowRect.top + window.scrollY && cursorPosition.y < rowRect.bottom + window.scrollY &&
                cursorPosition.x > rowRect.left + window.scrollX && cursorPosition.x < rowRect.right + window.scrollX) {
                // return the index of the targeted row
                return parseInt(row.attributes["data-rowindex"].value);
            }
        }    
        return -1;
    }
    razor

    Make sure that there is a PrimaryKey specified for the grid! The logic needs an unique identifier for the rows so they can be properly reordered.

    Una vez que RowDraggable esté habilitado y se haya definido una zona de colocación, debe implementar un controlador simple para el evento de colocación. Cuando se arrastra una fila, verifique lo siguiente:

    • ¿Se dejó caer la fila dentro de la cuadrícula?
    • Si es así, ¿en qué otra fila se soltó la fila arrastrada?
    • Una vez que haya encontrado la fila de destino, intercambie las ubicaciones de los registros en la matriz Data.

    A continuación, puedes ver esto implementado:

    ¡Con estos sencillos pasos, ha configurado una cuadrícula que permite reordenar filas mediante arrastrar y soltar! Puede ver el código anterior en acción en la siguiente demostración.

    Mantener presionado el ícono de arrastrar le permitirá mover una fila a cualquier lugar de la cuadrícula:

    EXAMPLE
    DATA
    MODULES
    RAZOR
    JS
    CSS

    Limitations

    Actualmente, no existen limitaciones conocidas para RowDraggable.

    API References

    Additional Resources

    Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.