Resúmenes de cuadrículas Angular
La cuadrícula de la interfaz de usuario de Angular en Ignite UI for Angular tiene una característica de resúmenes que funciona en un nivel por columna como pie de página de grupo. Angular resúmenes de cuadrícula es una característica poderosa que permite al usuario ver la información de la columna en un contenedor separado con un conjunto predefinido de elementos de resumen predeterminados, según el tipo de datos dentro de la columna o mediante la implementación de una plantilla angular personalizada en la cuadrícula.
Angular Grid Summaries Overview Example
Note
El resumen de la columna es una función de todos los valores de la columna; a menos que se aplique un filtrado, el resumen de la columna será función de los valores de los resultados filtrados.
Los resúmenes de cuadrícula también se pueden habilitar a nivel de columna en Ignite UI for Angular, lo que significa que solo puede activarlos para las columnas que necesite. Resúmenes de cuadrícula le proporciona un conjunto predefinido de resúmenes predeterminados, en función del tipo de datos de la columna, para que pueda ahorrar algo de tiempo:
For string and boolean data types, the following function is available:
- contar
For number, currency and percent data types, the following functions are available:
- contar
- mín.
- máximo
- promedio
- suma
For date data type, the following functions are available:
- contar
- más temprano
- el último
Todos los tipos de datos de columna disponibles se pueden encontrar en el tema oficial Tipos de columna.
Grid 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 igx-grid 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.
<igx-grid #grid1 [data]="data" [autoGenerate]="false" height="800px" width="800px" (columnInit)="initColumn($event)">
<igx-column field="ProductID" header="Product ID" width="200px" [sortable]="true"></igx-column>
<igx-column field="ProductName" header="Product Name" width="200px" [sortable]="true" [hasSummary]="true"></igx-column>
<igx-column field="ReorderLevel" width="200px" [editable]="true" [dataType]="'number'" [hasSummary]="true"></igx-column>
</igx-grid>
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 igx-grid.
<igx-grid #grid1 [data]="data" [autoGenerate]="false" height="800px" width="800px" (columnInit)="initColumn($event)" >
<igx-column field="ProductID" header="Product ID" width="200px" [sortable]="true"></igx-column>
<igx-column field="ProductName" header="Product Name" width="200px" [sortable]="true" [hasSummary]="true"></igx-column>
<igx-column field="ReorderLevel" width="200px" [editable]="true" [dataType]="'number'" [hasSummary]="false"></igx-column>
</igx-grid>
<button (click)="enableSummary()">Enable Summary</button>
<button (click)="disableSummary()">Disable Summary </button>
public enableSummary() {
this.grid1.enableSummaries([
{fieldName: 'ReorderLevel', customSummary: this.mySummary},
{fieldName: 'ProductID'}
]);
}
public disableSummary() {
this.grid1.disableSummaries('ProductName');
}
Custom Grid Summaries
If these functions do not fulfill your requirements you can provide a custom summary for the specific columns. In order to achieve this you have to override one of the base classes IgxSummaryOperand, IgxNumberSummaryOperand or IgxDateSummaryOperand according to the column data type and your needs. This way you can redefine the existing function or you can add new functions. IgxSummaryOperand class provides the default implementation only for the count method. IgxNumberSummaryOperand extends IgxSummaryOperand and provides implementation for the min, max, sum and average. IgxDateSummaryOperand extends IgxSummaryOperand and additionally gives you earliest and latest.
import { IgxSummaryResult, IgxSummaryOperand, IgxNumberSummaryOperand, IgxDateSummaryOperand } from 'igniteui-angular';
// import { IgxSummaryResult, IgxSummaryOperand, IgxNumberSummaryOperand, IgxDateSummaryOperand } from '@infragistics/igniteui-angular'; for licensed package
class MySummary extends IgxNumberSummaryOperand {
constructor() {
super();
}
operate(data?: any[]): IgxSummaryResult[] {
const result = super.operate(data);
result.push({
key: 'test',
label: 'Test',
summaryResult: data.filter(rec => rec > 10 && rec < 30).length
});
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 IgxSummaryResult.
interface IgxSummaryResult {
key: string;
label: string;
summaryResult: any;
}
y tomar parámetros opcionales para calcular los resúmenes. Consulte Resúmenes personalizados, que acceden a toda la sección de datos a continuación.
Note
In order to calculate the summary row height properly, the Grid needs the operate method to always return an array of IgxSummaryResult with the proper length even when the data is empty.
And now let's add our custom summary to the column UnitsInStock. We will achieve that by setting the summaries property to the class we create below.
<igx-grid #grid1 [data]="data" [autoGenerate]="false" height="800px" width="800px" (columnInit)="initColumn($event)" >
<igx-column field="ProductID" width="200px" [sortable]="true">
</igx-column>
<igx-column field="ProductName" width="200px" [sortable]="true" [hasSummary]="true">
</igx-column>
<igx-column field="UnitsInStock" width="200px" [dataType]="'number'" [hasSummary]="true" [summaries]="mySummary" [sortable]="true">
</igx-column>
<igx-column field="ReorderLevel" width="200px" [editable]="true" [dataType]="'number'" [hasSummary]="true">
</igx-column>
</igx-grid>
...
export class GridComponent implements OnInit {
mySummary = MySummary;
....
}
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 IgxSummaryOperand operate method.
As you can see in the code snippet below the operate method has the following three parameters:
- columnData: le proporciona una matriz que contiene los valores solo para la columna actual
- allGridData: le brinda toda la fuente de datos de la cuadrícula
- fieldName - campo de columna actual
class MySummary extends IgxNumberSummaryOperand {
constructor() {
super();
}
operate(columnData: any[], allGridData = [], fieldName?): IgxSummaryResult[] {
const result = super.operate(allData.map(r => r[fieldName]));
result.push({ key: 'test', label: 'Total Discontinued', summaryResult: allData.filter((rec) => rec.Discontinued).length });
return result;
}
}
Summary Template
igxSummary targets the column summary providing as a context the column summary results.
<igx-column ... [hasSummary]="true">
<ng-template igxSummary let-summaryResults>
<span> My custom summary template</span>
<span>{{ summaryResults[0].label }} - {{ summaryResults[0].summaryResult }}</span>
</ng-template>
</igx-column>
Cuando se define un resumen predeterminado, la altura del área de resumen se calcula por diseño en función de la columna con el mayor número de resúmenes y el tamaño de la cuadrícula. Use la propiedad de entrada summaryRowHeight para invalidar el valor predeterminado. Como argumento, espera un valor numérico y, al establecer un valor falso, se activará el comportamiento de tamaño predeterminado del pie de página de la cuadrícula.
Note
La plantilla de resumen de columna se puede definir a través de API estableciendo la propiedad SummaryTemplate de la columna en el TemplateRef requerido.
Disable Summaries
The disabledSummaries property provides precise per-column control over the Ignite UI for Angular grid summary feature. This property enables users to customize the summaries displayed for each column in the grid, 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.
Esta propiedad también se puede modificar dinámicamente en tiempo de ejecución a través del código, lo que proporciona flexibilidad para adaptar los resúmenes de la cuadrícula a los cambios en los estados de la aplicación o las acciones del usuario.
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 Ignite UI for Angular grid:
<!-- default summaries -->
<igx-column
field="UnitPrice"
header="Unit Price"
dataType="number"
[hasSummary]="true"
[disabledSummaries]="['count', 'sum', 'average']"
>
</igx-column>
<!-- custom summaries -->
<igx-column
field="UnitsInStock"
header="Units In Stock"
dataType="number"
[hasSummary]="true"
[summaries]="discontinuedSummary"
[disabledSummaries]="['discontinued', 'totalDiscontinued']"
>
</igx-column>
For UnitPrice, default summaries like count, sum, and average are disabled, leaving others like min and max active.
For UnitsInStock, custom summaries such as total 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.
Formatting summaries
By default, summary results, produced by the built-in summary operands, are localized and formatted according to the grid locale and column pipeArgs. When using custom operands, the locale and pipeArgs are not applied. If you want to change the default appearance of the summary results, you may format them using the summaryFormatter property.
public dateSummaryFormat(summary: IgxSummaryResult, summaryOperand: IgxSummaryOperand): string {
const result = summary.summaryResult;
if(summaryOperand instanceof IgxDateSummaryOperand && summary.key !== 'count'
&& result !== null && result !== undefined) {
const pipe = new DatePipe('en-US');
return pipe.transform(result,'MMM YYYY');
}
return result;
}
<igx-column ... [summaryFormatter]="dateSummaryFormat"></igx-column>
Summaries with Group By
When you have grouped by columns, the Grid allows you to change the summary position and calculation mode using the summaryCalculationMode and summaryPosition properties. Along with these two properties the IgxGrid 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: los resúmenes se calculan solo para el nivel raíz.
- childLevelsOnly: los resúmenes se calculan solo para los niveles secundarios.
- rootAndChildLevels: los resúmenes se calculan tanto para el nivel raíz como para el nivel secundario. Este es el valor predeterminado.
The available values of the summaryPosition property are:
- arriba: la fila de resumen aparece antes del grupo por fila secundaria.
- abajo: la fila de resumen aparece después del grupo por fila secundaria. Este es el valor predeterminado.
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 Grid.
Demo
Exporting Summaries
There is an exportSummaries option in IgxExcelExporterOptions that specifies whether the exported data should include the grid's summaries. Default exportSummaries value is false.
The IgxExcelExporterService will export the default summaries for all column types as their equivalent excel functions so they will continue working properly when the sheet is modified. Try it for yourself in the example below:
The exported file includes a hidden column that holds the level of each DataRecord in the sheet. This level is used in the summaries to filter out the cells that need to be included in the summary function.
En la siguiente tabla, puede encontrar la fórmula de Excel correspondiente a cada uno de los resúmenes predeterminados.
| Tipo de datos | Función | Función Excel |
|---|---|---|
string, boolean |
contar | ="Contar: "&CONTAR.SI(inicio:fin, nivel de registro) |
number, currency, percent |
contar | ="Contar: "&CONTAR.SI(inicio:fin, nivel de registro) |
| mín. | ="Min: "&MIN(IF(inicio:fin=nivel de registro, inicio de rango:fin de rango)) | |
| máximo | ="Máx: "&MAX(IF(inicio:fin=nivel de registro, inicio de rango:fin de rango)) | |
| promedio | ="Promedio: "&PROMEDIOIF(inicio:fin, nivel de registro, inicio de rango:fin de rango) | |
| suma | ="Suma: "&SUMIF(inicio:fin, nivel de registro, inicio de rango:fin de rango) | |
date |
contar | ="Contar: "&CONTAR.SI(inicio:fin, nivel de registro) |
| más temprano | ="Más temprano: "& TEXT(MIN(IF(start:end=recordLevel, rangeStart:rangeEnd)), formato) | |
| el último | ="Último: "&TEXT(MAX(IF(start:end=recordLevel, rangeStart:rangeEnd)), formato) |
Known Limitations
| Limitación | Descripción |
|---|---|
| Exportar resúmenes personalizados | Los resúmenes personalizados se exportarán como cadenas en lugar de funciones de Excel. |
| Exportar resúmenes con plantillas | Los resúmenes con plantilla no son compatibles y se exportarán como los predeterminados. |
Keyboard Navigation
Se puede navegar por las filas de resumen con las siguientes interacciones de teclado:
- ARRIBA: navega una celda hacia arriba
- ABAJO: navega una celda hacia abajo
- IZQUIERDA: navega una celda hacia la izquierda
- DERECHA: navega una celda hacia la derecha
- CTRL + IZQUIERDA o INICIO: navega a la celda más a la izquierda
- CTRL + DERECHA o FINAL: navega a la celda más a la derecha
Estilismo
To get started with styling the sorting behavior, we need to import the index file, where all the theme functions and component mixins live:
@use "igniteui-angular/theming" as *;
// IMPORTANT: Prior to Ignite UI for Angular version 13 use:
// @import '~igniteui-angular/lib/core/styles/themes/index';
Following the simplest approach, we create a new theme that extends the grid-summary-theme and accepts the $background-color, $focus-background-color, $label-color, $result-color, $pinned-border-width, $pinned-border-style and $pinned-border-color parameters.
$custom-theme: grid-summary-theme(
$background-color: #e0f3ff,
$focus-background-color: rgba(#94d1f7, .3),
$label-color: #e41c77,
$result-color: black,
$pinned-border-width: 2px,
$pinned-border-style: dotted,
$pinned-border-color: #e41c77
);
Note
Instead of hardcoding the color values like we just did, we can achieve greater flexibility in terms of colors by using the palette and color functions. Please refer to Palettes topic for detailed guidance on how to use them.
El último paso es incluir el tema personalizado del componente:
@include css-vars($custom-theme);
Note
If the component is using an Emulated ViewEncapsulation, it is necessary to penetrate this encapsulation using ::ng-deep:
:host {
::ng-deep {
@include css-vars($custom-theme);
}
}
Demo
API References
- API de componentes IgxGrid
- Estilos de componentes IgxGrid
- Estilos de resúmenes de IgxGrid
- IgxSummaryOperando
- IgxNúmeroResumenOperando
- IgxFechaResumenOperando
- Componente de grupo de columnas Igx
- ComponenteColumnaIgx
Additional Resources
- Descripción general de la cuadrícula
- Tipos de datos de columna
- Virtualización y rendimiento
- Paginación
- Filtración
- Clasificación
- Columna en movimiento
- Fijación de columnas
- Cambio de tamaño de columna
- Selección