Web Components Grid Group By

    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 exemplo apresenta os recursos de agrupamento de uma grande quantidade de dados. Arrastar os cabeçalhos de coluna para o topo (área de agrupamento) permite que os usuários vejam os dados da coluna selecionada em uma estrutura hierárquica. Eles podem agrupar por em vários campos arrastando mais cabeçalhos de coluna para o topo. Essas opções de agrupamento são úteis quando você tem tabelas com várias linhas e colunas nas quais os usuários desejam apresentar os dados de uma forma muito mais rápida e visualmente aceitável.

    Initial Grouping State

    É possível definir o agrupamento inicial da grade atribuindo uma matriz de expressões à groupingExpressions propriedade da grade.

    constructor() {
        var grid = document.getElementById("grid") as IgcGridComponent;
        grid.groupingExpressions = [
            { fieldName: 'ProductName', dir: SortingDirection.Desc },
            { fieldName: 'Released', dir: SortingDirection.Desc }
        ];
    }
    

    Expressões de agrupamento implementam a interface ISortingExpression.

    Group By API

    Grouping API

    O agrupamento está disponível por meio da IU e por meio de uma API robusta exposta pelo componente grid. Os desenvolvedores podem permitir que os usuários finais agrupem os dados da grade por determinadas colunas, definindo a propriedade Groupable de cada coluna como 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;
    

    Os grupos podem ser criados expandidos (padrão) ou recolhidos e os estados de expansão geralmente contêm apenas o estado oposto ao comportamento padrão. Você pode controlar se os grupos devem ser criados expandidos ou não por meio da groupsExpanded propriedade.

    Select/Deselect All Rows in a Group API

    Selecionar/desmarcar todas as linhas em um grupo está disponível por meio dos selectRowsInGroup métodos e deselectRowsInGroup API.

    O snippet de código abaixo pode ser usado para selecionar todas as linhas dentro de um grupo usando o método de instância selectRowsInGroup de registro de grupo. Além disso, o segundo parâmetro desse método é uma propriedade booleana por meio da qual você pode escolher se a seleção de linha anterior será desmarcada ou não. A seleção anterior é preservada por padrão.

        const groupRow = this.grid.getRowByIndex(0).groupRow;
        grid.selectRowsInGroup(groupRow);
    

    Se você precisar desmarcar todas as linhas dentro de um grupo programaticamente, poderá usar o deselectRowsInGroup método.

        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 exemplo, o modelo a seguir tornaria o resumo das linhas do grupo mais detalhado:

        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.

    A propriedade SelectedCount mostra quantos registros do grupo estão selecionados no momento, enquanto TotalCount mostra quantos registros pertencem ao grupo.

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

    A propriedade GroupRow retorna uma referência à linha do grupo.

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

    As propriedades SelectedCount e TotalCount podem ser usadas para determinar se o seletor de linha Group By deve ser verificado ou indeterminado (parcialmente selecionado).

    Web Components Grid Group By With Paging

    As linhas de grupo participam do processo de paginação junto com as linhas de dados. Elas contam para o tamanho de página para cada página. As linhas recolhidas não são incluídas no processo de paginação. Qualquer operação de expansão ou recolhimento força o Paging a recalcular a contagem de páginas e ajustar o índice de página, se necessário. Os grupos que abrangem várias páginas são divididos entre elas. A linha de grupo é visível apenas na página em que começa e não é repetida nas páginas subsequentes. As informações de resumo para linhas de grupo são calculadas com base no grupo inteiro e não são afetadas pelo Paging.

    Web Components Group By With Paging Example

    Group By With Summaries

    A integração entre Agrupar por e Resumos é descrita no tópico Resumos.

    Keyboard Navigation

    A interface de agrupamento oferece suporte às seguintes interações de teclado:

    • Para linhas de grupo (o foco deve estar na linha ou na célula de expansão/recolhimento)

      • ALT + DIREITA- Expande o grupo
      • ALT + ESQUERDA- Recolhe o grupo
      • ESPAÇO- seleciona todas as linhas no grupo, se a propriedade rowSelection estiver definida como múltipla
    • For group IgcChipComponent components in the group by area (focus should be on the chip)

      • SHIFT + ESQUERDA- move a ficha em foco para a esquerda, alterando a ordem de agrupamento, se possível
      • SHIFT + DIREITA- move o chip em foco para a direita, alterando a ordem de agrupamento, se possível
      • ESPAÇO- altera a direção da classificação
      • DELETE- desagrupa o campo
      • Os elementos separados do chip também são focalizáveis e podem ser interagidos usando a tecla ENTER.

    Web Components Grid Custom Group By

    Grid allows defining custom grouping per column or per grouping expression, which provides grouping based on a custom condition. This is useful when you need to group by complex objects or for other application specific scenarios.

    O exemplo abaixo demonstra o agrupamento personalizado por Date, em que os valores de data são classificados e agrupados por Dia, Semana, Mês ou Ano com base no modo de agrupamento selecionado pelo usuário.

    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

    Além dos temas predefinidos, a grade pode ser ainda mais personalizada ao definir algumas das propriedades CSS disponíveis. Caso você queira alterar algumas das cores, precisa definir uma classe para a grade primeiro:

    <igc-grid class="grid">
    

    Em seguida, defina as propriedades CSS relacionadas para essa classe:

    .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

    Limitação Descrição
    A quantidade máxima de colunas agrupadas é 10. Se mais de 10 colunas forem agrupadas, um erro será gerado.

    API References

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.