Angular Agrupar cuadrícula por

    A Group By behavior in an Ignite UI for Angular Table or UI Grid creates grouped data rows based on the column values. The Group By in igxGrid allows for visualizing the groups in a hierarchical structure. The grouped data rows can be expanded or collapsed and the order of grouping may be changed through the UI or API. When Row Selection is enabled, a Group By row selector is rendered in the left-most area of the group row. In case the rowSelection property is set to single, checkboxes are disabled and only serve as an indication for the group where selection is placed. If the rowSelection property is set to multiple, clicking over the Group By row selector selects all records belonging to this group.

    Angular Grid Group By Example

    Este ejemplo presenta las capacidades de agrupación de una gran cantidad de datos. Arrastrar los encabezados de las columnas a la parte superior (área de agrupación) permite a los usuarios ver los datos de la columna seleccionada en una estructura jerárquica. Pueden agrupar en varios campos arrastrando más encabezados de columna a la parte superior. Estas opciones de agrupación resultan útiles cuando tienes tablas con numerosas filas y columnas donde los usuarios quieren presentar los datos de una manera mucho más rápida y visualmente aceptable.

    Initial Grouping State

    It is possible to define initial grouping of the grid by assigning an array of expressions to the groupingExpressions property of the grid.

    public ngOnInit() {
        grid.groupingExpressions = [
            { fieldName: 'ProductName', dir: SortingDirection.Desc },
            { fieldName: 'Released', dir: SortingDirection.Desc }
        ];
    }
    

    Grouping expressions implement the ISortingExpression interface.

    Group By API

    Grouping API

    Grouping is available through the UI and through a robust API exposed by the grid component. Developers can allow end-users to group the grid data by certain columns, by setting each column's groupable property to true.

    <igx-grid [data]="data">
        <igx-column *ngFor="let c of columns" [field]="c.field" [groupable]="true">
        </igx-column>
    </igx-grid>
    
    public ngOnInit() {
        grid.columns.forEach((column) => {
            column.groupable = true;
        });
    }
    

    During runtime the expressions are gettable and settable from the groupingExpressions property. If you need to add or change an existing expression you may also use the groupBy method with either a single or an array of ISortingExpression.

    grid.groupBy({ fieldName: 'ProductName', dir: SortingDirection.Desc, ignoreCase: true });
    
    Note

    Hasta ahora, la agrupación/clasificación funcionaba en conjunto. En la versión 13.2, se introduce un nuevo comportamiento que desacopla la agrupación de la ordenación. Por ejemplo, al borrar la agrupación, no se borrarán las expresiones de ordenación en la cuadrícula o viceversa. Aun así, si una columna está ordenada y agrupada, las expresiones agrupadas tienen prioridad.

    Expand/Collapse API

    In addition to grouping expressions you can also control the expansion states for group rows. They are stored in a separate property of the igxGrid component groupingExpansionState. A group row is uniquely identified based on the field name it is created for and the value it represents for each level of grouping. This means that the signature of an expansion state interface is the following:

    export interface IGroupByKey {
        fieldName: string;
        value: any;
    }
    
    export interface IGroupByExpandState {
        hierarchy: Array<IGroupByKey>;
        expanded: boolean;
    }
    

    As with groupingExpressions, setting a list of IGroupByExpandState directly to the groupingExpansionState will change the expansion accordingly. Additionally igxGrid exposes a method that toggles a group by the group record instance.

        const groupRow = this.grid.groupsRecords.find(r => r.value === "France");
        const groupRow = this.grid.getRowByIndex(0).groupRow;
        grid.toggleGroup(groupRow);
        groupRow.expanded = false;
    

    Groups can be created expanded (default) or collapsed and the expansion states would generally only contain the state opposite to the default behavior. You can control whether groups should be created expanded or not through the groupsExpanded property.

    Select/Deselect all rows in a group API

    Selecting/Deselecting all rows in a group is available through the selectRowsInGroup and deselectRowsInGroup API methods.

    The code snippet below can be used to select all rows within a group using the group record instance selectRowsInGroup method. Additionally, the second parameter of this method is a boolean property through which you may choose whether the previous row selection will be cleared or not. The previous selection is preserved by default.

        const groupRow = this.grid.groupsRecords.find(r => r.value === "France");
        const groupRow = this.grid.getRowByIndex(0).groupRow;
        grid.selectRowsInGroup(groupRow);
    

    If you need to deselect all rows within a group programmatically, you can use the deselectRowsInGroup method.

        const groupRow = this.grid.groupsRecords.find(r => r.value === "France");
        const groupRow = this.grid.getRowByIndex(0).groupRow;
        grid.deselectRowsInGroup(groupRow);
    

    Templating

    Group Row Templates

    La fila del grupo, excepto la interfaz de usuario para expandir/contraer, es totalmente adaptable a plantillas. De forma predeterminada, muestra un icono de agrupación y muestra el nombre del campo y el valor que representa. La plantilla de registro de agrupación con la que se presenta tiene la siguiente firma:

    export interface IGroupByRecord {
        expression: ISortingExpression;
        level: number;
        records: GroupedRecords;
        value: any;
        groupParent: IGroupByRecord;
        groups?: IGroupByRecord[];
    }
    

    Como ejemplo, la siguiente plantilla haría que el resumen de filas del grupo fuera más detallado:

    <ng-template igxGroupByRow let-groupRow>
        <span>Total items with value: {{ groupRow.value }} are {{ groupRow.records.length }}</span>
    </ng-template>
    

    Group Row Selector Templates

    As mentioned above the group row except for the expand/collapse UI is fully templatable. To create a custom Group By row selector template within the Grid, declare an <ng-template> with igxGroupByRowSelector directive. From the template, you can access the implicitly provided context variable, with properties that give you information about the Group By row's state.

    The selectedCount property shows how many of the group records are currently selected while totalCount shows how many records belong to the group.

    <ng-template igxGroupByRowSelector let-groupByRowContext>
        {{ groupByRowContext.selectedCount }} / {{ groupByRowContext.totalCount  }}
    </ng-template>
    

    The groupRow property returns a reference to the group row.

    <ng-template igxGroupByRowSelector let-groupByRowContext>
        <div (click)="handleGroupByRowSelectorClick($event, groupByRowContext.groupRow)">Handle groupRow</div>
    </ng-template>
    

    The selectedCount and totalCount properties can be used to determine if the Group By row selector should be checked or indeterminate (partially selected).

    <igx-grid #grid [data]="gridData" primaryKey="ProductID" rowSelection="multiple">
        <!-- ... -->
        <ng-template igxGroupByRowSelector let-context>
            <igx-checkbox
                [checked]=" context.selectedCount > 0 && context.selectedCount === context.totalCount"
                [indeterminate]="context.selectedCount > 0 && context.selectedCount !== context.totalCount">
            </igx-checkbox>
        </ng-template>
    </igx-grid>
    

    Angular Grid Group By with Paging

    Las filas de grupo participan en el proceso de paginación junto con las filas de datos. Cuentan para el tamaño de página de cada página. Las filas contraídas no se incluyen en el proceso de paginación. Cualquier operación de expandir o contraer obliga a Paging a recalcular el recuento de páginas y ajustar el índice de páginas si es necesario. Los grupos que abarcan varias páginas se dividen entre ellos. La fila del grupo es visible solo en la página en la que comienza y no se repite en las páginas siguientes. La información de resumen de las filas del grupo se calcula en función de todo el grupo y no se ve afectada por la paginación.

    Angular group by with paging example

    Group By with Summaries

    La integración entre Agrupar por y Resúmenes se describe en el tema Resúmenes.

    Keyboard Navigation

    La interfaz de usuario de agrupación admite las siguientes interacciones de teclado:

    • Para filas de grupo (el foco debe estar en la fila o en la celda expandir/contraer)

      • ALT + DERECHA: expande el grupo
      • ALT + IZQUIERDA: colapsa el grupo
      • ESPACIO: selecciona todas las filas del grupo, si la propiedad RowSelection está establecida en múltiples
    • For group igxChip components in the group by area (focus should be on the chip)

      • MAYÚS + IZQUIERDA: mueve el chip enfocado hacia la izquierda, cambiando el orden de agrupación, si es posible
      • MAYÚS + DERECHA: mueve el chip enfocado hacia la derecha, cambiando el orden de agrupación, si es posible
      • ESPACIO: cambia la dirección de clasificación
      • ELIMINAR: desagrupa el campo
      • Los elementos separados del chip también se pueden enfocar y se puede interactuar con ellos mediante la ENTER llave.

    Angular Grid Custom Group By

    igxGrid permite definir agrupaciones personalizadas por columna o por expresión de agrupación, lo que proporciona agrupaciones basadas en una condición personalizada. Esto es útil cuando necesita agrupar por objetos complejos o para otros escenarios específicos de aplicaciones.

    Note

    In order to implement custom grouping the data first needs to be sorted appropriately. Due to this you may also need to apply a custom sorting strategy that extends the base DefaultSortingStrategy. After the data is sorted the custom groups can be determined by specifying a groupingComparer for the column or for the specific grouping expression.

    The sample below demonstrates custom grouping by Date, where the date values are sorted and grouped by Day, Week, Month or Year based on user-selected grouping mode.

    Angular custom group by example

    The sample defines custom sorting strategies for the different date conditions. Each custom strategy extends the base DefaultSortingStrategy and defines the compareValues method, which is the custom compare function used when sorting the values. Additionally it extracts the values from the date needed for the comparison.

    class BaseSortingStrategy extends DefaultSortingStrategy {
    
        public getParsedDate(date: any) {
            return {
                day: date.getDay(),
                month: date.getMonth() + 1,
                year: date.getFullYear()
            };
        }
    
        compareValues(a: any, b: any) {
            const dateA = this.getParsedDate(a);
            const dateB = this.getParsedDate(b);
            return dateA.year < dateB.year ?
                -1 : dateA.year > dateB.year ?
                1 : dateA.month  < dateB.month ?
                -1 : dateA.month > dateB.month ?
                1 : 0;
        }
    }
    
    class DaySortingStrategy extends BaseSortingStrategy {
        compareValues(a: any, b: any) {
            const dateA = this.getParsedDate(a);
            const dateB = this.getParsedDate(b);
            return dateA.year < dateB.year ?
                -1 : dateA.year > dateB.year ?
                1 : dateA.month  < dateB.month ?
                -1 : dateA.month > dateB.month ?
                1 : dateA.day < dateB.day ?
                -1 : dateA.day > dateB.day ?
                1 : 0;
        }
    }
    
    class WeekSortingStrategy extends BaseSortingStrategy {
    
        public getWeekOfDate(a: any) {
           return parseInt(new DatePipe("en-US").transform(a, 'w'), 10);
        }
    
        compareValues(a: any, b: any) {
            const dateA = this.getParsedDate(a);
            const dateB = this.getParsedDate(b);
            const weekA = this.getWeekOfDate(a);
            const weekB = this.getWeekOfDate(b);
            return dateA.year < dateB.year ?
                -1 : dateA.year > dateB.year ?
                1 : weekA < weekB ?
                -1 : weekA > weekB ?
                1 : 0;
        }
    }
    

    A groupingComparer function is defined for the grouping expressions, which determines the items belonging to the same group based on the selected grouping mode. Values in the sorted data for which this function returns 0 are marked as part of the same group.

     groupingComparer: (a, b) => {
        const dateA = this.sortingStrategy.getParsedDate(a);
        const dateB = this.sortingStrategy.getParsedDate(b);
        if (this.groupByMode === 'Month') {
            return dateA.month === dateB.month ? 0 : -1;
        } else if (this.groupByMode === "Year") {
            return dateA.year === dateB.year ? 0 : -1;
        } else if (this.groupByMode === "Week") {
            return this.sortingStrategy.getWeekOfDate(a) === this.sortingStrategy.getWeekOfDate(b) ? 0 : -1;
        }
        return dateA.day === dateB.day && dateA.month === dateB.month ? 0 : -1;
    }
    

    From version 15.1.0, you can also use the built-in sorting strategy GroupMemberCountSortingStrategy to sort items based on members count.

    public sortByGroup() {
            const expressions = this.grid1.groupingExpressions;
            if (expressions.length) {
                const fieldName = expressions[0].fieldName;
                const dir = expressions[0].dir === SortingDirection.Asc ? SortingDirection.Desc : SortingDirection.Asc;
                this.grid1.groupBy({ fieldName, dir, ignoreCase: false, strategy: GroupMemberCountSortingStrategy.instance() });
            }
        }
    

    Estilismo

    The igxGrid allows styling through the Ignite UI for Angular Theme Library. The grid's grid-theme exposes a wide variety of properties, which allow the customization of all the features of the grid.

    En los pasos siguientes, veremos los pasos para personalizar el estilo Agrupar por de la cuadrícula.

    Importing global theme

    To begin the customization of the Group By feature, you need to import the index file, where all styling functions and mixins are located.

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

    Defining custom theme

    Next, create a new theme, that extends the grid-theme and accepts the parameters, required to customize the Group By as desired. You also need to extend the chip-theme, because it's used in the Group By feature.

    
    $custom-theme: grid-theme(
      $group-row-background: #494949,
      $group-row-selected-background: #383838,
      $group-label-column-name-text: #f8f8f8,
      $group-label-icon: #ffcd0f,
      $group-label-text: #f8f8f8,
      $group-count-background: #ffcd0f,
      $group-count-text-color: #000,
      $expand-icon-color: #ffcd0f,
      $expand-icon-hover-color: rgb(223, 181, 13),
      $cell-active-border-color: #ffcd0f,
      $row-selected-background: #fff6d3,
      $row-selected-text-color: #000,
      $drop-indicator-color: #ffcd0f
    );
    
    /* Chip theme will style the chips in the Group By area */
    $custom-chips-theme: chip-theme(
      $background: #494949,
      $text-color: #f8f8f8,
      $hover-text-color: #e7e7e7
    );
    

    Defining a custom color palette

    In the approach that we described above, the color values were hardcoded. Alternatively, you can achieve greater flexibility, using the palette and color functions. palette generates a color palette, based on provided primary, secondary and surface colors.

    $black-color: #292826;
    $yellow-color: #ffcd0f;
    $grey-color: #efefef;
    
    $custom-palette: palette(
      $primary: $black-color, 
      $secondary: $yellow-color, 
      $surface: $grey-color
    );
    

    After a custom palette has been generated, the color function can be used to obtain different varieties of the primary and the secondary colors.

    $custom-theme: grid-theme(
      $group-row-background: color($custom-palette, "primary", 300),
      $group-row-selected-background: color($custom-palette, "primary", 400),
      $group-label-column-name-text:contrast-color($custom-palette, "primary", 500),
      $group-label-icon: color($custom-palette, "secondary", 600),
      $group-label-text:contrast-color($custom-palette, "primary", 500),
      $group-count-background: color($custom-palette, "secondary", 600),
      $group-count-text-color: color($custom-palette, "primary", 400),
      $expand-icon-color: color($custom-palette, "secondary", 600),
      $expand-icon-hover-color: color($custom-palette, "secondary", 300),
      $cell-active-border-color: color($custom-palette, "secondary", 600)
    );
    
    $custom-chips-theme: chip-theme(
      $background: color($custom-palette, "primary", 300),
      $text-color:contrast-color($custom-palette, "primary", 500),
      $hover-text-color:contrast-color($custom-palette, "primary", 600)
    );
    

    Defining custom schemas

    You can go even further and build flexible structure that has all the benefits of a schema. The schema is the recipe of a theme. Extend one of the two predefined schemas, that are provided for every component. In our case, we would use light-grid.

    $custom-grid-schema: extend(
      map.get('grid', $light-material-schema),
      (
        group-row-background: (color:('secondary', 100)),
        group-row-selected-background: (color:('primary', 400)),
        group-label-column-name-text: (color:('primary', 600)),
        group-label-icon: (color:('primary', 600)),
        group-label-text: (color:('secondary', 700)),
        group-count-background: (color:('primary', 600)),
        group-count-text-color: (color:('secondary', 400)),
        expand-icon-color: (color:('primary', 600)),
        expand-icon-hover-color: (color:('primary', 400))
      )
    );
    

    In order for the custom schema to be applied, either (light or dark) globals has to be extended. The whole process is actually supplying a component with a custom schema and adding it to the respective component theme afterwards.

    $my-custom-schema: extend(
      $light-material-schema, 
      ( 
        grid: $custom-grid-schema
      )
    );
    
    $custom-theme: grid-theme(
      $palette: $custom-palette,
      $schema: $my-custom-schema
    );
    

    Applying the custom theme

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

    @include css-vars($custom-theme);
    @include css-vars($custom-chips-theme);
    

    Scoped component theme

    In order for the custom theme to affect only specific component, you can move all of the styles you just defined from the global styles file to the custom component's style file (including the import of the index file).

    De esta manera, debido a Angular ViewEncapsulation, los estilos solo se aplicarán al componente personalizado.

    Note

    If the component is using an Emulated ViewEncapsulation, it is necessary to penetrate this encapsulation using ::ng-deep in order to style the components which are inside the grid.

    In our example, we need to use ::ng-deep for our chip theme:

    @include css-vars($custom-theme);
    
    :host {
      ::ng-deep {
        @include chip($custom-chips-theme);
      }
    }
    

    Demo

    Note

    La muestra no se verá afectada por el tema global seleccionado deChange Theme.

    Known Limitations

    Limitación Descripción
    La cantidad máxima de columnas agrupadas es 10. Si se agrupan más de 10 columnas, se genera un error.

    API References

    Additional Resources

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