Edición de celdas en cuadrícula jerárquica Angular

    Ignite UI for Angular componente de cuadrícula jerárquica proporciona una gran capacidad de manipulación de datos y una potente API para Angular operaciones CRUD. De forma predeterminada, la cuadrícula jerárquica se utiliza en la edición de celdas y se mostrarán diferentes editores según el tipo de datos de la columna, gracias a la plantilla de edición de celdas predeterminada. Además, puede definir sus propias plantillas personalizadas para las acciones de actualización de datos y para invalidar el comportamiento predeterminado para confirmar y descartar cualquier cambio.

    Angular Hierarchical Grid cell editing and edit templates Example

    Note

    By using igxCellEditor with any type of editor component, the keyboard navigation flow will be disrupted. The same applies to direct editing of the custom cell that enters edit mode. This is because the focus will remain on the cell element, not on the editor component that we've added - igxSelect, igxCombo, etc. This is why we should take leverage of the igxFocus directive, which will move the focus directly in the in-cell component and will preserve a fluent editing flow of the cell/row.

    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;
    • on key press Enter;
    • on key press F2;

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

    • on key press Escape;
    • cuando realiza operaciones de clasificación, filtrado, búsqueda y ocultación;

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

    • on key press Enter;
    • on key press F2;
    • on key press Tab;
    • con un solo clic en otra celda: cuando haga clic en otra celda en la cuadrícula jerárquica, se enviarán sus cambios.
    • 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

    La celda permanece en modo de edición cuando se desplaza vertical u horizontalmente o hace clic fuera de la cuadrícula jerárquica. Esto es válido tanto para la edición de celdas como para la edición de filas.

    Editing through API

    También puede modificar el valor de la celda a través de la API IgxHierarchicalGrid, pero solo si está definida la clave principal:

    public updateCell() {
        this.hierarchicalGrid.updateCell(newValue, rowID, 'Age');
    }
    

    Another way to update cell is directly through update method of IgxGridCell:

    public updateCell() {
        const cell = this.hierarchicalGrid.getCellByColumn(rowIndex, 'ReorderLevel');
        // You can also get cell by rowID if primary key is defined
        // cell = this.hierarchicalGrid.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.

    If you want to provide a custom template which will be applied when a cell is in edit mode, you can make use of the igxCellEditor directive. To do this, you need to pass an ng-template marked with the igxCellEditor directive and properly bind your custom control to the cell.editValue:

    <igx-column field="class" header="Class" [editable]="true">
        <ng-template igxCellEditor let-cell="cell" let-value>
            <igx-select class="cell-select" [(ngModel)]="cell.editValue" [igxFocus]="true">
                <igx-select-item *ngFor="let class of classes" [value]="class">
                    {{ class }}
                </igx-select-item>
            </igx-select>
        </ng-template>
    </igx-column>
    

    This code is used in the sample below which implements an IgxSelectComponent in the cells of the Race, Class and Alignment columns.

    Note

    Any changes made to the cell's editValue in edit mode, will trigger the appropriate editing event on exit and apply to the transaction state (if transactions are enabled).

    Note

    The cell template igxCell controls how a column's cells are shown when outside of edit mode. The cell editing template directive igxCellEditor, handles how a column's cells in edit mode are displayed and controls the edited cell's edit value.

    Note

    By using igxCellEditor with any type of editor component, the keyboard navigation flow will be disrupted. The same applies to direct editing of the custom cell that enters edit mode. This is because the focus will remain on the cell element, not on the editor component that we've added - igxSelect, igxCombo, etc. This is why we should take leverage of the igxFocus directive, which will move the focus directly in the in-cell component and will preserve a fluent editing flow of the cell/row.

    Para obtener más información sobre cómo configurar columnas y sus plantillas, puede consultar la documentación para la configuración de Columnas de cuadrícula.

    CRUD operations

    Note

    Tenga en cuenta que cuando realice alguna operación CRUD, todas las canalizaciones aplicadas, como filtrado, clasificación y agrupación, se volverán a aplicar y su vista se actualizará automáticamente.

    The IgxHierarchicalGridComponent provides a straightforward API for basic CRUD operations.

    Adding a new record

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

    public addRow() {
        // Adding a new record
        // Assuming we have a `getNewRecord` method returning the new row data
        const record = this.getNewRecord();
        this.hierarchicalGrid.addRow(record, 1);
    }
    

    Updating data in the Hierarchical Grid

    Updating data in the Hierarchical Grid is achieved through updateRow and updateCell methods but only if primary key 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.hierarchicalGrid.updateRow(newData, this.selectedCell.cellID.rowID);
    
    // Just a particular cell through the Grid API
    this.hierarchicalGrid.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.hierarchicalGrid.getRowByKey(rowID);
    row.update(newData);
    

    Deleting data from the Hierarchical Grid

    Please keep in mind that deleteRow() method will remove the specified row only if primary key is defined.

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

    Estos pueden conectarse a interacciones del usuario, no necesariamente relacionadas con igx-hierarchical-grid; por ejemplo, un clic en un botón:

    <button igxButton igxRipple (click)="deleteRow($event)">Delete Row</button>
    

    Cell validation on edit event

    Using the grid's editing events we can alter how the user interacts with the grid. 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 (event.cancel = true). We'll also display a custom error message using IgxToast.

    Lo primero que debemos hacer es vincularnos al evento de la grilla:

    <igx-hierarchical-grid (cellEdit)="handleCellEdit($event)"
    ...>
    ...
    </igx-hierarchical-grid>
    

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

    export class MyHGridEventsComponent {
        public handleCellEdit(event: IGridEditEventArgs) {
            const today = new Date();
            const column = event.column;
            if (column.field === 'Debut') {
                if (event.newValue > today.getFullYear()) {
                    this.toast.message = 'The debut date must be in the past!';
                    this.toast.open();
                    event.cancel = true;
                }
            } else if (column.field === 'LaunchDate') {
                if (event.newValue > new Date()) {
                    this.toast.message = 'The launch date must be in the past!';
                    this.toast.open();
                    event.cancel = true;
                }
            }
        }
    }
    

    Aquí, estamos validando dos columnas. Si el usuario intenta cambiar el año de debut de un artista o la fecha de lanzamiento de un álbum, la cuadrícula no permitirá fechas posteriores a la actual.

    The result of the above validation being applied to our igx-hierarchical-grid can be seen in the below demo:

    Estilismo

    The IgxHierarchicalGrid allows for its cells to be styled through the Ignite UI for Angular Theme Library. The grid's grid-theme exposes a wide range of properties, which allow users to style many different aspects of the grid.

    En los pasos a continuación, veremos cómo puede diseñar la celda de la cuadrícula en modo de edición y cómo puede definir el alcance de esos estilos.

    In order to use the Ignite UI Theming Library, we must first import the theme index file in our global styles:

    Importing style library

    @use "igniteui-angular/theming" as *;
    
    // IMPORTANT: Prior to Ignite UI for Angular version 13 use:
    // @import '~igniteui-angular/lib/core/styles/themes/index';
    

    Ahora podemos hacer uso de todas las funciones expuestas por el motor de temas Ignite UI for Angular.

    Defining a palette

    After we've properly imported the index file, we create a custom palette that we can use. Let's define three colors that we like and use them to build a palette with palette:

    $white: #fff;
    $blue: #4567bb;
    $gray: #efefef;
    
    $color-palette: palette(
      $primary: $white, 
      $secondary: $blue, 
      $surface: $gray
    );
    

    Defining themes

    We can now define the theme using our palette. The cells are styled by the grid-theme, so we can use that to generate a theme for our IgxHierarchicalGrid:

    $custom-grid-theme: grid-theme(
      $cell-editing-background: $blue,
      $cell-edited-value-color: $white,
      $cell-active-border-color: $white,
      $edit-mode-color: color($color-palette, "secondary", 200)
    );
    

    Applying the theme

    The easiest way to apply our theme is with a sass @include statement in the global styles file:

    @include grid($custom-grid-theme);
    

    Demo

    In addition to the steps above, we can also style the controls that are used for the cells' editing templates: input-group, datepicker & checkbox

    Note

    The sample will not be affected by the selected global theme from Change Theme.

    API References

    Additional Resources