Web Components Agrupar cuadrícula por

    The Ignite UI for Web Components Group By behavior in Web Components IgcGrid creates grouped data rows based on the column values. The Group By in the IgcGridComponent 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.

    Web Components 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.

    constructor() {
        var grid = document.getElementById("grid") as IgcGridComponent;
        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.

    <igc-grid auto-generate="false" id="grid">
        <igc-column field="OrderID" hidden="true"></igc-column>
        <igc-column field="ShipCountry" header="Ship Country" width="200px" groupable="true"> </igc-column>
        <igc-column field="OrderDate" header="Order Date" data-type="date" width="200px" groupable="true"> </igc-column>
        <igc-column field="PostalCode" header="Postal Code" width="200px" groupable="true"> </igc-column>
        <igc-column field="Discontinued" width="200px" data-type="boolean" groupable="true" name="column1" id="column1"> </igc-column>
        <igc-column field="ShipName" header="Ship Name" width="200px" groupable="true"> </igc-column>
        <igc-column field="ShipCity" header="Ship City" width="200px" groupable="true"> </igc-column>
        <igc-column field="ShipperName" header="Shipper Name" width="200px" groupable="true"> </igc-column>
        <igc-column field="Salesperson" header="Sales Person" width="200px" groupable="true"> </igc-column>
        <igc-column field="UnitPrice" header="Unit Price" width="200px" groupable="true"> </igc-column>
        <igc-column field="Quantity" width="200px" groupable="true"> </igc-column>
    </igc-grid>
    
        constructor() {
            var column1 = (this.column1 = document.getElementById("column1") as IgcColumnComponent);
            column1.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 expressions.

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

    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 IgcGridComponent component groupingExpansionState which is a collection of IgcGroupByExpandState. Each expansion state is uniquely defined by the field name it is created for and the value it represents for each level of grouping, i.e. the identifier is a hierarchy array of IgcGroupByKey.

    As with groupingExpressions, setting a list of IgcGroupByExpandState directly to the groupingExpansionState will change the expansion accordingly. Additionally IgcGridComponent exposes a method toggleGroup that toggles a group by the group record instance or via the expanded property of the row.

    const groupRow = this.grid.getRowByIndex(0).groupRow;
    grid.toggleGroup(groupRow);
    
    const groupRow = this.grid.getRowByIndex(0);
    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.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.getRowByIndex(0).groupRow;
    grid.deselectRowsInGroup(groupRow);
    

    Templating

    Group Row Templates

    The group row except for the expand/collapse UI is fully templatable. By default it renders a grouping icon and displays the field name and value it represents. The context to render the template against is of type IgcGroupByRecord.

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

        public groupByRowTemplate = (ctx: IgcGroupByRowTemplateContext) => {
            const groupRow: IgcGroupByRecord = ctx.implicit;
            return html`<span>Total items with value: ${ groupRow.value } are ${ groupRow.records.length }</span>`;
        }
    

    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 use groupByRowSelectorTemplate. 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.

    public groupByRowSelectorTemplate = (ctx: IgcGroupByRowSelectorTemplateContext) => {
        return html`
            ${ ctx.implicit.selectedCount } / ${ ctx.implicit.totalCount  }
        `;
    }
    

    The groupRow property returns a reference to the group row.

    public groupByRowSelectorTemplate = (ctx: IgcGroupByRowSelectorTemplateContext) => {
        const groupRow = ctx.implicit.groupRow;
        return html` <div @click=${(e: any) => this.handleGroupByRowSelectorClick(e, groupRow)} ">Handle groupRow</div> `;
    };
    

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

    Web Components 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.

    Web Components 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 IgcChipComponent 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.

    Web Components Grid Custom Group By

    Grid 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.

    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.

    Web Components Custom Group By Example

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

    public groupByMode = "Month";
    public getParsedDate(date: any) {
        return {
            day: date.getDay(),
            month: date.getMonth() + 1,
            year: date.getFullYear()
        };
    }
    

    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.

    grid.groupingExpressions = [
        { fieldName: 'OrderDate', dir: SortingDirection.Desc,
        groupingComparer: (a, b) => {
                const dateA = this.getParsedDate(a);
                const dateB = this.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.getWeekOfDate(a) === this.getWeekOfDate(b) ? 0 : -1;
                }
                return dateA.day === dateB.day && dateA.month === dateB.month ? 0 : -1;
            }
        }
    ];
    

    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">
    

    Luego configure las propiedades CSS relacionadas para esa clase:

    .grid {
        --ig-grid-group-row-background: #969799;
        --ig-grid-group-row-selected-background: #969799;
        --ig-grid-group-label-column-name-text: #f8f8f8;
        --ig-grid-group-label-text: #f8f8f8;
        --ig-grid-group-count-text-color: #222;
        --ig-grid-expand-icon-color: #f8f8f8;
        --ig-grid-expand-icon-hover-color: #f8f8f8;
    }
    

    Demo

    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.