Edición de filas de cuadrícula jerárquica Angular

    La cuadrícula jerárquica proporciona una forma conveniente de realizar manipulaciones de datos mediante la edición en línea y una API potente para operaciones CRUD Angular. Haga clic en una fila y presione la tecla Enter o simplemente haga doble clic con el mouse en la fila que necesita modificarse.

    Angular Hierarchical Grid Row Editing Example

    El siguiente ejemplo demuestra cómo habilitar la edición de filas en la cuadrícula jerárquica. Cambiar el valor de una celda y luego hacer clic o navegar a otra celda en la misma fila no actualizará el valor de la fila hasta que se confirme usando el botón Listo o se descarte usando el botón Cancelar.

    Note

    Cuando una fila está en modo de edición, al hacer clic en una celda de otra fila se actuará como si se presionara el botón Listo: envíe todos los cambios de la fila anterior. Si la nueva celda que recibe el foco es editable, entonces la nueva fila también ingresa al modo de edición, mientras que si la celda no es editable, solo la fila anterior sale del modo de edición.

    Row Editing Usage

    To get started import the IgxHierarchicalGridModule in the app.module.ts file:

    // app.module.ts
    
    ...
    import { IgxHierarchicalGridModule } from 'igniteui-angular';
    
    @NgModule({
        ...
        imports: [..., IgxHierarchicalGridModule],
        ...
    })
    export class AppModule {}
    

    Then define a Hierarchical Grid with bound data source and rowEditable set to true:

    <igx-hierarchical-grid [data]="localdata" [autoGenerate]="false" [rowEditable]="true">
        <igx-column field="Artist" [editable]="true" [dataType]="'string'"></igx-column>
        <igx-column field="HasGrammyAward" [editable]="true" [dataType]="'boolean'">
        </igx-column>
        <igx-column field="Debut" [editable]="true" [dataType]="'number'"></igx-column>
        <igx-column field="GrammyNominations" [editable]="true" [dataType]="'number'" [hasSummary]="true"></igx-column>
        <igx-column field="GrammyAwards" [editable]="true" [dataType]="'number'"
        [hasSummary]="true"></igx-column>
        <igx-column width="10%">
            <ng-template igxCell let-cell="cell">
                <button igxIconButton="flat" (click)="removeRow(cell.cellID.rowIndex)">
                    <igx-icon>delete</igx-icon>
                </button>
            </ng-template>
        </igx-column>
    
        <igx-row-island [key]="'Albums'" #layout1 [autoGenerate]="false">
            <igx-column field="Album" [editable]="true" [dataType]="'string'"></igx-column>
            <igx-column field="Launch Date" [editable]="true" [dataType]="'date'"></igx-column>
            <igx-column field="Billboard Review" [editable]="true" [dataType]="'number'"></igx-column>
            <igx-column field="US Billboard 200" [editable]="true" [dataType]="'number'"></igx-column>
            <igx-row-island [key]="'Songs'" [autoGenerate]="false">
                <igx-column field="No."></igx-column>
                <igx-column field="Title"></igx-column>
                <igx-column field="Released"></igx-column>
                <igx-column field="Genre"></igx-column>
            </igx-row-island>
        </igx-row-island>
    </igx-hierarchical-grid>
    
    Note

    La configuración de la clave principal es obligatoria para las operaciones de edición de filas.

    Note

    It's not needed to enable editing for individual columns. Using the rowEditable property in the Hierarchical Grid, will mean that all rows, with defined field property, excluding primary one, will be editable. If you want to disable editing for specific column, then you set the editable column's input to false.

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { IgxRowIslandComponent, IgxHierarchicalGridComponent } from 'igniteui-angular';
    // import { IgxRowIslandComponent, IgxHierarchicalGridComponen } from '@infragistics/igniteui-angular'; for licensed package
    import { SINGERS } from './data';
    
    @Component({
        selector: 'hierarchical-grid-row-editing',
        styleUrls: ['./hierarchical-grid-row-editing.component.scss'],
        templateUrl: 'hierarchical-grid-row-editing.component.html'
    })
    
    export class HGridRowEditingSampleComponent implements OnInit {
        public localdata;
    
        @ViewChild('layout1')
        layout1: IgxRowIslandComponent;
    
        @ViewChild('hierarchicalGrid')
        hierarchicalGrid: IgxHierarchicalGridComponent;
    
        constructor() {
            this.localdata = SINGERS;
        }
    }
    
    Note

    The Hierarchical Grid uses internally a provider IgxBaseTransactionService that holds pending cell changes, until row state submitted or cancelled.

    Positioning

    • La posición predeterminada de la superposición estará debajo de la fila que está en modo de edición.

    • Si no hay espacio debajo de la fila, aparecerá una superposición encima de la fila.

    • Una vez que se muestra, arriba o abajo, la superposición mantendrá esta posición durante el desplazamiento, hasta que se cierre la superposición.

    Behavior

    • Si la fila está en modo de edición, la edición continuará si se hace clic en una celda de la misma fila.

    • Al hacer clic en el botón "Listo", finalizará la edición de la fila y enviará los cambios a la fuente de datos o a una transacción, si está disponible. Además, la fila saldrá del modo de edición.

    • Al hacer clic en el botón "Cancelar", se revertirán todos los cambios actuales en la fila y la fila saldrá del modo de edición.

    • Si la fila está en modo de edición, al hacer clic en una celda de otra fila finalizará la edición de la fila actual y se enviarán nuevos cambios en la fila (el mismo comportamiento al hacer clic en el botón "Listo"). Si la nueva celda que recibe el foco es editable, entonces la nueva fila también ingresa al modo de edición, mientras que si la celda no es editable, solo la fila anterior sale del modo de edición.

    • Si la fila está en modo de edición y la cuadrícula jerárquica se desplaza de modo que esa fila salga del área visible, esta última seguirá en modo de edición. Cuando se desplaza la cuadrícula jerárquica, para que la fila vuelva a ser visible, la fila seguirá en modo de edición. Cuando se hace clic fuera de la cuadrícula jerárquica, la celda también permanecerá en modo de edición.

    • Al realizar operaciones de clasificación, filtrado, búsqueda y ocultación, se revertirán todos los cambios actuales en la fila y la fila saldrá del modo de edición.

    • Al realizar operaciones de paginación, cambio de tamaño, fijación y movimiento, saldrá del modo de edición y enviará el último valor.

    • Cada celda modificada obtiene un estilo editado hasta que finaliza la edición de la fila. Este es el comportamiento cuando la cuadrícula jerárquica no cuenta con transacciones. Cuando las transacciones están disponibles, se aplica el estilo de edición de celda hasta que se confirmen todos los cambios.

    Keyboard Navigation

    • Enter and F2 enters row edit mode

    • Esc exits row edit mode and doesn't submit any of the cell changes, made while the row was in edit mode.

    • Tab move focus from one editable cell in the row to the next and from the right-most editable cell to the CANCEL and DONE buttons. Navigation from DONE button goes to the left-most editable cell within the currently edited row.

    Feature Integration

    • Cualquier operación de cambio de datos finalizará las operaciones de edición de filas y enviará los cambios de filas actuales. Esto incluirá operaciones como ordenar, cambiar criterios de agrupación y filtrado, paginación, etc.

    • Los resúmenes se actualizarán una vez finalizada la edición de la fila. Lo mismo es válido para otras funciones como ordenar, filtrar, etc.

    Customizing Row Editing Overlay

    Customizing Text

    Customizing the text of the row editing overlay is possible using the igxRowEditTextDirective. The rowChangesCount property is exposed and it holds the count of the changed cells.

    <ng-template igxRowEditText let-rowChangesCount>
     Changes: {{rowChangesCount}}
    </ng-template>
    

    Customizing Buttons

    Customizing the buttons of the row editing overlay is possible using the igxRowEditActionsDirective. If you want the buttons to be part of the keyboard navigation, then each on of them should have the igxRowEditTabStopDirective.

    <ng-template igxRowEditActions let-endRowEdit>
    <button igxButton igxRowEditTabStop (click)="endRowEdit(false)">Cancel</button>
    <button igxButton igxRowEditTabStop (click)="endRowEdit(true)">Apply</button>
    </ng-template>
    

    Estilismo

    Using the Ignite UI for Angular Theme Library, we can greatly alter the Row Editing overlay. The Row Editing overlay is a composite element - its UI is comprised of a couple of other components: - igx-banner in order to render its contents - igx-buttons are rendered in the default template (for the Done and Cancel buttons).

    In the below example, we will make use of those two components' styling options, button styling & banner-styling, to customize the experience of our IgxHierarchicalGrid's Row Editing. We will also style the current cell's editor and background to make it more distinct. You can learn more about cell styling in the Cell Styling section.

    Import theme

    The easiest way to style the Row Editing banner is to define styles in our app's global style file (typically styles.scss). The first thing we need to do is import the themes/index file - this gives us access to all the powerful tools of the Ignite UI for Angular Sass framework:

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

    Una vez que hayamos importado el archivo de temas, podemos crear temas personalizados.

    Definir el tema

    We can now define a custom banner theme that will affect our Row Editing background and make use of one of the predefined palettes namely $purple-palette :

    $banner-theme: banner-theme(
      $banner-background: #e3e3e3,
      $banner-message-color: color($purple-palette, "secondary", 600)
    );
    

    Here we are using my-banner-palette in conjunction with igx-color (exposed by the theme library) for generating our colors.

    Include the theme

    All we have to do now is apply the theme with a Sass @include statement. We pass our newly defined $banner-theme through the css-vars mixin:

    @include css-vars($banner-theme);
    

    Component styles

    Dado que la superposición de edición de filas hace uso de muchos temas de otros componentes, el estilo a través de los estilos globales puede afectar a otras partes de nuestra aplicación (por ejemplo, banners, botones, etc.). La mejor manera de evitarlo es limitar el tema del banner al archivo de estilo del componente específico al que se aplica.

    Note

    If the component is using an Emulated ViewEncapsulation, it is necessary to penetrate this encapsulation using ::ng-deep in order to style the grid Row Editing Overlay.

    // custom.component.scss
    
    :host {
      ::ng-deep {
        @include css-vars($banner-theme);
      }
    }
    

    Con la sintaxis anterior, nuestro tema de banner personalizado se aplica correctamente a la superposición de edición de filas de la cuadrícula.

    Custom Templates

    To further customize our Row Editing overlay, we can pass a custom template so we can style the Done and Cancel buttons separately:

    <!-- in component.html -->
    <igx-hierarchical-grid>
        <ng-template igxRowEditActions let-endRowEdit>
            <div class="custom-buttons">
                <button igxIconButton="flat" class="custom-button" igxRowEditTabStop (click)="endRowEdit(false)">
                    <igx-icon>clear</igx-icon>
                </button>
                <button igxIconButton="flat" class="custom-button" igxRowEditTabStop (click)="endRowEdit(true)">
                    <igx-icon>check</igx-icon>
                </button>
            </div>
        </ng-template>
    </igx-hierarchical-grid>
    

    After we've defined our custom buttons, we can make use of the button-theme to style them. You can learn more about igx-button styling in the Button Styling documentation. We can create a custom theme for our Done and Cancel:

    // custom.component.scss
    ...
    
    $button-theme: button-theme(
      $palette: $purple-palette
    );
    
    ...
    .custom-buttons {
      @include css-vars($button-theme);
    }
    

    We scope our @include statement in .custom-buttons so that it is only applied to the Doneand Cancel buttons.

    Demo

    Después de diseñar el banner y los botones, también definimos un estilo personalizado para la celda en modo de edición. El resultado de todos los estilos combinados se puede ver a continuación:

    Note

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

    Known Issues and Limitations

    • When the grid has no primaryKey set and remote data scenarios are enabled (when paging, sorting, filtering, scrolling trigger requests to a remote server to retrieve the data to be displayed in the grid), a row will lose the following state after a data request completes:
      • Selección de fila
      • Fila Expandir/contraer
      • Edición de filas
      • Fijación de filas

    API References

    Additional Resources

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