Resumos da grade Blazor

    The Ignite UI for Blazor Summaries feature in Blazor Grid functions on a per-column level as group footer. Blazor IgbGrid summaries is powerful feature which enables the user to see column information in a separate container with a predefined set of default summary items, depending on the type of data within the column or by implementing a custom template in the IgbGrid.

    Blazor Grid Summaries Overview Example

    [!Note] The summary of the column is a function of all column values, unless filtering is applied, then the summary of the column will be function of the filtered result values

    IgbGrid summaries can also be enabled on a per-column level in Ignite UI for Blazor, which means that you can activate it only for columns that you need. IgbGrid summaries gives you a predefined set of default summaries, depending on the type of data in the column, so that you can save some time:

    For string and boolean DataType, the following function is available:

    • Contar

    For number, currency and percent data types, the following functions are available:

    • Contar
    • Mínimo
    • Máx.
    • Média
    • Soma

    For date data type, the following functions are available:

    • Contar
    • Mais antigo
    • Mais recente

    Todos os tipos de dados de coluna disponíveis podem ser encontrados no tópico oficial Tipos de coluna.

    IgbGrid summaries are enabled per-column by setting HasSummary property to true. It is also important to keep in mind that the summaries for each column are resolved according to the column data type. In the IgbGrid the default column data type is string, so if you want number or date specific summaries you should specify the DataType property as number or date. Note that the summary values will be displayed localized, according to the grid Locale and column PipeArgs.

    <IgbGrid>
            <IgbColumn Field="EmployeeID" DataType="GridColumnDataType.Number" HasSummary="true"></IgbColumn>
            <IgbColumn Field="FirstName" HasSummary="true"></IgbColumn>
            <IgbColumn Field="LastName" HasSummary="true"></IgbColumn>
            <IgbColumn Field="Title" HasSummary="true"></IgbColumn>
    </IgbGrid>
    

    The other way to enable/disable summaries for a specific column or a list of columns is to use the public method EnableSummaries/DisableSummaries of the IgbGrid.

     <IgbGrid @ref=grid Id="grid" AutoGenerate="false">
            <IgbColumn Field="EmployeeID" DataType="GridColumnDataType.Number" HasSummary="true"></IgbColumn>
            <IgbColumn Field="FirstName" Sortable="true" HasSummary="true"></IgbColumn>
            <IgbColumn Field="LastName" Sortable="false" DisablePinning="true" DisableHiding="true" HasSummary="true"></IgbColumn>
            <IgbColumn Field="Title" Sortable="true" DisablePinning="false" DisableHiding="true"></IgbColumn>
    </IgbGrid>
    
    @code {
        public async void DisableSummaries()
        {
            object[] disabledSummaries = { "EmployeeID" };
            await this.grid.DisableSummariesAsync(disabledSummaries);
        }
    }
    

    Custom Grid Summaries

    Se essas funções não atenderem aos seus requisitos, você pode fornecer um resumo personalizado para as colunas específicas.

    
    //In JavaScript
    class WebGridDiscontinuedSummary {
        operate(data, allData, fieldName) {
            const discontinuedData = allData.filter((rec) => rec['Discontinued']).map(r => r[fieldName]);
            const result = [];
            result.push({
                key: 'products',
                label: 'Products',
                summaryResult: data.length
            });
            result.push({
                key: 'total',
                label: 'Total Items',
                summaryResult: data.length ? data.reduce((a, b) => +a + +b) : 0
            });
            result.push({
                key: 'discontinued',
                label: 'Discontinued Products',
                summaryResult: allData.map(r => r['Discontinued']).filter((rec) => rec).length
            });
            result.push({
                key: 'totalDiscontinued',
                label: 'Total Discontinued Items',
                summaryResult: discontinuedData.length ? discontinuedData.reduce((a, b) => +a + +b) : 0
            });
            return result;
        }
    }
    

    As seen in the examples, the base classes expose the Operate method, so you can choose to get all default summaries and modify the result, or calculate entirely new summary results.

    The method returns a list of IgbSummaryResult.

    e tomar parâmetros opcionais para calcular os resumos. Consulte a seção Resumos personalizados, que acessam todos os dados abaixo.

    [!Note] In order to calculate the summary row height properly, the Grid needs the Operate method to always return an array of IgbSummaryResult with the proper length even when the data is empty.

    <IgbGrid
            AutoGenerate="true"
            Name="grid"
            @ref="grid"
            Data="NwindData"
            PrimaryKey="ProductID"
            ColumnInitScript="WebGridCustomSummary">
    </IgbGrid>
    
    // In Javascript
    igRegisterScript("WebGridCustomSummary", (event) => {
        if (event.detail.field === "UnitsInStock") {
            event.detail.summaries = WebGridDiscontinuedSummary;
        }
    }, false);
    

    Custom summaries, which access all data

    Now you can access all Grid data inside the custom column summary. Two additional optional parameters are introduced in the SummaryOperand Operate method. As you can see in the code snippet below the operate method has the following three parameters:

    • columnData - fornece uma matriz que contém os valores apenas para a coluna atual
    • allGridData - fornece a fonte de dados da grade completa
    • fieldName - campo da coluna atual
    class WebGridDiscontinuedSummary {
        operate(data, allData, fieldName) {
            const discontinuedData = allData.filter((rec) => rec['Discontinued']).map(r => r[fieldName]);
            result.push({
                key: 'totalDiscontinued',
                label: 'Total Discontinued Items',
                summaryResult: discontinuedData.length ? discontinuedData.reduce((a, b) => +a + +b) : 0
            });
            return result;
        }
    }
    

    Summary Template

    SummaryTemplate targets the column summary providing as a context the column summary results.

    <IgbColumn HasSummary="true" SummaryTemplateScript="SummaryTemplate">
    </IgbColumn>
    
    igRegisterScript("SummaryTemplate", (ctx) => {
        var html = window.igTemplating.html;
        return html`<div>
        <span> ${ctx.implicit[0].label} - ${ctx.implicit[0].summaryResult} </span>
    </div>`
    }, false);
    

    When a default summary is defined, the height of the summary area is calculated by design depending on the column with the largest number of summaries and the --ig-size of the grid. Use the SummaryRowHeight input property to override the default value. As an argument it expects a number value, and setting a falsy value will trigger the default sizing behavior of the grid footer.

    Disabled Summaries

    The DisabledSummaries property provides precise per-column control over the Blazor Grid summary feature. This property enables users to customize the summaries displayed for each column in the IgbGrid, ensuring that only the most relevant and meaningful data is shown. For example, you can exclude specific summary types, such as ['count', 'min', 'max'] by specifying their summary keys in an array.

    Essa propriedade também pode ser modificada dinamicamente em tempo de execução por meio de código, fornecendo flexibilidade para adaptar os resumos do IgbGrid à alteração dos estados do aplicativo ou das ações do usuário.

    The following examples illustrate how to use the DisabledSummaries property to manage summaries for different columns and exclude specific default and custom summary types in the Blazor Grid:

    <!-- Disable default summaries -->
    <IgbColumn
        Field="UnitPrice"
        Header="Unit Price"
        DataType="GridColumnDataType.Number"
        HasSummary="true"
        DisabledSummaries="['count', 'sum', 'average']" />
    
    <!-- Disable custom summaries -->
    <IgbColumn
        Field="UnitsInStock"
        Header="Units In Stock"
        DataType="GridColumnDataType.Number"
        HasSummary="true"
        Summaries="discontinuedSummary"
        DisabledSummaries="['discontinued', 'totalDiscontinued']" />
    

    For UnitPrice, default summaries like count, sum, and average are disabled, leaving others like min and max active.

    For UnitsInStock, custom summaries such as discontinued and totalDiscontinued are excluded using the DisabledSummaries property.

    At runtime, summaries can also be dynamically disabled using the DisabledSummaries property. For example, you can set or update the property on specific columns programmatically to adapt the displayed summaries based on user actions or application state changes.

    Summaries with Group By

    When you have grouped by columns, the IgbGrid allows you to change the summary position and calculation mode using the SummaryCalculationMode and SummaryPosition properties. Along with these two properties the IgbGrid exposes and ShowSummaryOnCollapse property which allows you to determine whether the summary row stays visible when the group row that refers to is collapsed.

    The available values of the SummaryCalculationMode property are:

    • RootLevelOnly - Summaries are calculated only for the root level.
    • ChildLevelsOnly - Summaries are calculated only for the child levels.
    • RootAndChildLevels - Summaries are calculated for both root and child levels. This is the default value.

    The available values of the SummaryPosition property are:

    • Top - The summary row appears before the group by row children.
    • Bottom - The summary row appears after the group by row children. This is the default value.

    The ShowSummaryOnCollapse property is boolean. Its default value is set to false, which means that the summary row would be hidden when the group row is collapsed. If the property is set to true the summary row stays visible when group row is collapsed.

    [!Note] The SummaryPosition property applies only for the child level summaries. The root level summaries appear always fixed at the bottom of the IgbGrid.

    Demo

    Keyboard Navigation

    As linhas de resumo podem ser navegadas com as seguintes interações de teclado:

    • PARA CIMA- navega uma célula para cima.
    • PARA BAIXO- navega uma célula para baixo.
    • ESQUERDA- navega uma célula para a esquerda.
    • DIREITA- navega uma célula para a direita.
    • CTRL + ESQUERDA ou HOME- navega para a célula mais à esquerda.
    • CTRL + DIREITA ou END- navega para a célula mais à direita.

    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:

    <IgbGrid class="grid"></IgbGrid>
    

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

    .grid {
        --ig-grid-summary-background-color:#e0f3ff;
        --ig-grid-summary-focus-background-color: rgba( #94d1f7, .3 );
        --ig-grid-summary-label-color: rgb(228, 27, 117);
        --ig-grid-summary-result-color: black;
    }
    

    Demo

    API References

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.