Web Components Edición de celdas de cuadrícula

    La edición de celdas Ignite UI for Web Components en Web Components Grid proporciona una gran capacidad de manipulación de datos del contenido de celdas individuales dentro del componente Web Components Grid y viene con una potente API para operaciones CRUD React. Es una característica fundamental en aplicaciones como hojas de cálculo, tablas de datos y cuadrículas de datos, lo que permite a los usuarios agregar, editar o actualizar datos dentro de celdas específicas. De forma predeterminada, la cuadrícula de Ignite UI for Web Components se utiliza en la edición de celdas. Y debido a la plantilla de edición de celdas predeterminada, habrá diferentes editores basados en el tipo de datos de columna Top of Form.

    Además, puede definir sus propias plantillas personalizadas para acciones de actualización de datos y anular el comportamiento predeterminado para confirmar y descartar cualquier cambio.

    Web Components Grid Cell Editing and Edit Templates Example

    Edición de celdas

    Editing through UI

    Puede ingresar al modo de edición para una celda específica, cuando una celda editable está enfocada de una de las siguientes maneras:

    • al hacer doble clic;
    • con un solo clic: un solo clic ingresará al modo de edición solo si la celda seleccionada previamente estaba en modo de edición y la celda actualmente seleccionada es editable. Si la celda previamente seleccionada no estaba en modo de edición, un solo clic seleccionará la celda sin ingresar al modo de edición;
    • al presionar una ENTER tecla;
    • en la tecla presione F2;

    Puede salir del modo de edición sin realizar los cambios de una de las siguientes maneras:

    • en la tecla presione Escape;
    • cuando realizas operaciones de ordenación, filtrado, búsqueda y ocultación;

    Puede salir del modo de edición y confirmar los cambios de una de las siguientes maneras:

    • al presionar una ENTER tecla;
    • en la tecla presione F2;
    • al presionar una TAB tecla;
    • on single click to another cell - when you click on another cell in the IgcGridComponent, your changes will be submitted.
    • operaciones como paginación, cambio de tamaño, anclar o mover saldrán del modo de edición y se enviarán los cambios.

    [!Note] The cell remains in edit mode when you scroll vertically or horizontally or click outside the IgcGridComponent. This is valid for both cell editing and row editing.

    Editing through API

    You can also modify the cell value through the IgcGridComponent API but only if primary key is defined:

    public updateCell() {
        this.grid1.updateCell(newValue, rowID, 'ReorderLevel');
    }
    

    Another way to update cell is directly through Update method of Cell:

    public updateCell() {
        const cell = this.grid1.getCellByColumn(rowIndex, 'ReorderLevel');
        // You can also get cell by rowID if primary key is defined
        // cell = this.grid1.getCellByKey(rowID, 'ReorderLevel');
        cell.update(70);
    }
    

    Cell Editing Templates

    Puede ver y obtener más información sobre las plantillas de edición de celdas predeterminadas en el tema de edición general.

    Si desea proporcionar una plantilla personalizada que se aplicará a una celda, puede pasar dicha plantilla a la celda misma o a su encabezado. Primero cree la columna como lo haría normalmente:

    <igc-column
        field="Race"
        data-type="string"
        editable="true"
        id="column1">
    </igc-column>
    

    y pase las plantillas a esta columna en el archivo index.ts:

    constructor() {
        var grid1 = document.getElementById('grid1') as IgcGridComponent;
        var column1 = document.getElementById('column1') as IgcColumnComponent;
        var column2 = document.getElementById('column2') as IgcColumnComponent;
        var column3 = document.getElementById('column3') as IgcColumnComponent;
    
        grid1.data = this.webGridCellEditSampleRoleplay;
        column1.inlineEditorTemplate = this.webGridCellEditCellTemplate;
        column2.inlineEditorTemplate = this.webGridCellEditCellTemplate;
        column3.inlineEditorTemplate = this.webGridCellEditCellTemplate;
    }
    
    
    public webGridCellEditCellTemplate = (ctx: IgcCellTemplateContext) => {
        let cellValues: any = [];
        let uniqueValues: any = [];
        for(const i of (this.webGridCellEditSampleRoleplay as any)){
            const field: string = ctx.cell.column.field;
            if(uniqueValues.indexOf(i[field]) === -1 )
            {
                cellValues.push(html`<igc-select-item value=${i[field]}>${(i[field])}</igc-select-item>`);
                uniqueValues.push(i[field]);
            }
        }
        return html`
            <igc-select style="width:100%; height:100%" size="large" @igcChange=${(e: any) => ctx.cell.editValue = e.detail.value}>
                ${cellValues}
            </igc-select>
        `;
    }
    

    Puede encontrar una muestra funcional de lo anterior aquí para mayor referencia:

    Grid Excel Style Editing

    El uso de la edición de estilo de Excel permite al usuario navegar a través de las celdas tal como lo haría con Excel y editarlas muy rápidamente.

    Implementing this custom functionality can be done by utilizing the events of the IgcGridComponent. First we hook up to the grid's keydown events, and from there we can implement two functionalities:

    • Modo de edición constante
    public keydownHandler(event) {
      const key = event.keyCode;
      const grid = this.grid;
      const activeElem = grid.navigation.activeNode;
    
      if ((key >= 48 && key <= 57) ||
          (key >= 65 && key <= 90) ||
          (key >= 97 && key <= 122)) {
            // Number or Alphabet upper case or Alphabet lower case
            const columnName = grid.getColumnByVisibleIndex(activeElem.column).field;
            const cell = grid.getCellByColumn(activeElem.row, columnName);
            if (cell && !grid.crudService.cellInEditMode) {
                grid.crudService.enterEditMode(cell);
                cell.editValue = event.key;
            }
        }
    }
    
    • ENTER / SHIFT + ENTER navegación
    if (key == 13) {
        let thisRow = activeElem.row;
        const column = activeElem.column;
        const rowInfo = grid.dataView;
    
        // to find the next eligible cell, we will use a custom method that will check the next suitable index
        let nextRow = this.getNextEditableRowIndex(thisRow, rowInfo, event.shiftKey);
    
        // and then we will navigate to it using the grid's built in method navigateTo
        this.grid.navigateTo(nextRow, column, (obj) => {
            obj.target.activate();
            this.grid.clearCellSelection();
            this.cdr.detectChanges();
        });
    }
    

    Las partes clave para encontrar el próximo índice elegible serían:

    //first we check if the currently selected cell is the first or the last
    if (currentRowIndex < 0 || (currentRowIndex === 0 && previous) || (currentRowIndex >= dataView.length - 1 && !previous)) {
        return currentRowIndex;
    }
    // in case using shift + enter combination, we look for the first suitable cell going up the field
    if (previous) {
        return  dataView.findLastIndex((rec, index) => index < currentRowIndex && this.isEditableDataRecordAtIndex(index, dataView));
    }
    // or for the next one down the field
    return dataView.findIndex((rec, index) => index > currentRowIndex && this.isEditableDataRecordAtIndex(index, dataView));
    

    Consulte la muestra completa para obtener más referencias:

    Ejemplo de edición de estilo de Excel de cuadrícula de Web Components

    Los principales beneficios del enfoque anterior incluyen:

    • Modo de edición constante: al escribir mientras se selecciona una celda, se ingresará inmediatamente al modo de edición con el valor ingresado, reemplazando el existente
    • Las filas que no son de datos se omiten al navegar con ENTER / SHIFT + ENTER. Esto permite a los usuarios recorrer rápidamente sus valores.

    CRUD operations

    [!Note] Please keep in mind that when you perform some CRUD operation all of the applied pipes like filtering, sorting and grouping will be re-applied and your view will be automatically updated.

    The IgcGridComponent provides a straightforward API for basic CRUD operations.

    Adding a new record

    The IgcGridComponent component exposes the addRow method which will add the provided data to the data source itself.

    // Adding a new record
    // Assuming we have a `getNewRecord` method returning the new row data.
    const record = this.getNewRecord();
    this.grid.addRow(record);
    

    Updating data in the Grid

    Updating data in the Grid is achieved through updateRow and updateCell methods but only if the PrimaryKey for the grid is defined. You can also directly update a cell and/or a row value through their respective update methods.

    // Updating the whole row
    this.grid.updateRow(newData, this.selectedCell.cellID.rowID);
    
    // Just a particular cell through the Grid API
    this.grid.updateCell(newData, this.selectedCell.cellID.rowID, this.selectedCell.column.field);
    
    // Directly using the cell `update` method
    this.selectedCell.update(newData);
    
    // Directly using the row `update` method
    const row = this.grid.getRowByKey(rowID);
    row.update(newData);
    

    Deleting data from the Grid

    Please keep in mind that deleteRow method will remove the specified row only if a primaryKey is defined.

    // Delete row through Grid API
    this.grid.deleteRow(this.selectedCell.cellID.rowID);
    // Delete row through row object
    const row = this.grid.getRowByIndex(rowIndex);
    row.delete();
    

    Cell Validation on Edit Event

    Using the IgcGridComponent's editing events, we can alter how the user interacts with the IgcGridComponent.

    In this example, we'll validate a cell based on the data entered in it by binding to the CellEdit event. If the new value of the cell does not meet our predefined criteria, we'll prevent it from reaching the data source by cancelling the event.

    Lo primero que tenemos que hacer es enlazar al evento de la cuadrícula:

    constructor() {
        var grid = document.getElementById('grid') as IgcGridComponent;
        this.webGridCellEdit = this.webGridCellEdit.bind(this);
        grid.addEventListener("cellEdit", this.webGridCellEdit);
    }
    

    The CellEdit emits whenever any cell's value is about to be committed. In our CellEdit definition, we need to make sure that we check for our specific column before taking any action:

    public webGridCellEdit(event: CustomEvent<IgcGridEditEventArgs>): void {
        const column = event.detail.column;
        if (column.field === 'UnitsOnOrder') {
                const rowData = event.detail.rowData;
                if (!rowData) {
                    return;
                }
                if (event.detail.newValue > rowData.UnitsInStock) {
                    event.cancel = true;
                    alert("You cannot order more than the units in stock!");
                }
        }
    }
    
    

    Si el valor ingresado en una celda debajo de la columna Unidades en pedido es mayor que la cantidad disponible (el valor en Unidades en stock), la edición se cancelará y se alertará al usuario sobre la cancelación.

    The result of the above validation being applied to our IgcGridComponent can be seen in the below demo:

    Styling

    Además de los temas predefinidos, la cuadrícula se puede personalizar aún más configurando algunas de las propiedades CSS disponibles. En caso de que desee cambiar algunos de los colores, primero debe establecer una clase para la cuadrícula:

    <igc-grid class="grid"></igc-grid>
    

    Luego configure las propiedades CSS relacionadas para esa clase:

    .grid {
        --ig-grid-edit-mode-color: orange;
        --ig-grid-cell-editing-background: lightblue;
    }
    

    Styling Example

    API References

    Additional Resources