Angular Tree Grid Summaries
A grade da interface do usuário do Angular em Ignite UI for Angular tem um recurso de resumos que funciona em um nível por coluna como rodapé de grupo. Angular resumos de grade é um recurso poderoso que permite ao usuário ver as informações da coluna em um contêiner separado com um conjunto predefinido de itens de resumo padrão, dependendo do tipo de dados dentro da coluna ou implementando um modelo angular personalizado na grade de árvore.
Angular Tree Grid Summaries Overview Example
Note
O resumo da coluna é uma função de todos os valores de coluna, a menos que a filtragem seja aplicada, o resumo da coluna será função dos valores de resultado filtrados
Os resumos da Grade de Árvore também podem ser ativados em um nível por coluna no Ignite UI for Angular, o que significa que você pode ativá-lo apenas para as colunas necessárias. Os resumos da Grade de Árvore fornecem um conjunto predefinido de resumos padrão, dependendo do tipo de dados na coluna, para que você possa economizar algum tempo:
Parastring eboolean data types, a seguinte função está disponível:
- contar
Paranumber ecurrencypercent tipos de dados, as seguintes funções estão disponíveis:
- contar
- mínimo
- máx.
- média
- soma
Para odate tipo de dado, as seguintes funções estão disponíveis:
- contar
- mais cedo
- mais recente
Todos os tipos de dados de coluna disponíveis podem ser encontrados no tópico oficial Tipos de coluna.
Tree 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-tree-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-tree-grid #grid1 [data]="data" [autoGenerate]="false" height="800px" width="800px" (columnInit)="initColumn($event)">
<igx-column field="ID" header="Order ID" width="200px" [sortable]="true"></igx-column>
<igx-column field="Name" header="Order Product" width="200px" [sortable]="true" [hasSummary]="true"></igx-column>
<igx-column field="Units" width="200px" [editable]="true" [dataType]="'number'" [hasSummary]="true"></igx-column>
</igx-tree-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-tree-grid.
<igx-tree-grid #grid1 [data]="data" [autoGenerate]="false" height="800px" width="800px" (columnInit)="initColumn($event)" >
<igx-column field="ID" header="Order ID" width="200px" [sortable]="true"></igx-column>
<igx-column field="Name" header="Order Product" width="200px" [sortable]="true" [hasSummary]="true" ></igx-column>
<igx-column field="Units" width="200px" [editable]="true" [dataType]="'number'" [hasSummary]="false"></igx-column>
</igx-tree-grid>
<button (click)="enableSummary()">Enable Summary</button>
<button (click)="disableSummary()">Disable Summary </button>
public enableSummary() {
this.grid1.enableSummaries([
{fieldName: 'Units', customSummary: this.mySummary},
{fieldName: 'ID'}
]);
}
public disableSummary() {
this.grid1.disableSummaries('Name');
}
Custom Tree 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/core';
// 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;
}
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 Tree 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 UnitPrice. We will achieve that by setting the summaries property to the class we create below.
<igx-tree-grid #grid1 [data]="data" [autoGenerate]="false" height="800px" width="800px" (columnInit)="initColumn($event)">
<igx-column field="ID" header="Order ID" width="200px" [sortable]="true"></igx-column>
<igx-column field="Name" header="Order Product" width="200px" [sortable]="true" [hasSummary]="true"></igx-column>
<igx-column field="Units" [dataType]="'number'" width="200px" [editable]="true" [hasSummary]="true" [summaries]="mySummary"></igx-column>
<igx-column field="UnitPrice" header="Unit Price" width="200px" [dataType]="'number'" [dataType]="'currency'" [hasSummary]="true"></igx-column>
</igx-tree-grid>
...
export class GridComponent implements OnInit {
mySummary = MySummary;
....
}
Custom summaries, which access all data
Now you can access all Tree 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 - 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 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 Undelivered', 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>
Quando um resumo padrão é definido, a altura da área de resumo é calculada por design, dependendo da coluna com o maior número de resumos e do tamanho da grade. Use a propriedade de entrada summaryRowHeight para substituir o valor padrão. Como argumento, ele espera um valor numérico e definir um valor falso acionará o comportamento de dimensionamento padrão do rodapé da grade.
Note
O modelo de resumo de coluna pode ser definido por meio da API definindo a propriedade summaryTemplate da coluna como o TemplateRef necessário.
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.
Essa propriedade também pode ser modificada dinamicamente em tempo de execução por meio de código, fornecendo flexibilidade para adaptar os resumos da grade às mudanças nos estados do aplicativo ou nas 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 Ignite UI for Angular grid:
<!-- custom summaries -->
<igx-column
field="Units"
header="Units"
dataType="number"
[hasSummary]="true"
[summaries]="unitsSummary"
[disabledSummaries]="['uniqueCount', 'maxDifference']"
>
</igx-column>
<!-- default summaries -->
<igx-column
field="UnitPrice"
header="Unit Price"
dataType="number"
[hasSummary]="true"
[disabledSummaries]="['count', 'sum', 'average']"
>
</igx-column>
ParaUnits resumos personalizados comototalDelivered etotalNotDelivered são excluídos usando adisabledSummaries propriedade.
PoisUnitPrice, resumos padrão comocount,sum, eaverage estão desativados, deixando outros comomin emax ativos.
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>
Child Summaries
The Tree Grid supports separate summaries for the root nodes and for each nested child node level. Which summaries are shown is configurable using the summaryCalculationMode property. The child level summaries can be shown before or after the child nodes using the summaryPosition property. Along with these two properties the IgxTreeGrid exposes and showSummaryOnCollapse property which allows you to determine whether the summary row stays visible when the parent node that refers to is collapsed.
Os valores disponíveis dosummaryCalculationMode imóvel são:
- rootLevelOnly - Os resumos são calculados apenas para os nós de nível raiz.
- childLevelsOnly - Os resumos são calculados apenas para os níveis filho.
- rootAndChildLevels - Resumos são calculados para níveis raiz e filho. Este é o valor padrão.
Os valores disponíveis dosummaryPosition imóvel são:
- top - A linha de resumo aparece antes da lista de linhas filho.
- bottom - A linha de resumo aparece após a lista de linhas filho. Esse é o valor padrão.
The showSummaryOnCollapse property is boolean. Its default value is set to false, which means that the summary row would be hidden when the parent row is collapsed. If the property is set to true the summary row stays visible when parent 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 Tree Grid.
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.
Na tabela abaixo, você pode encontrar a fórmula do Excel correspondente para cada um dos resumos padrão.
| Tipo de dados | Função | Função Excel |
|---|---|---|
string, boolean |
contar | ="Contagem: "&CONT.SE(início:fim, recordLevel) |
number, currency, percent |
contar | ="Contagem: "&CONT.SE(início:fim, recordLevel) |
| mínimo | ="Min: "&MIN(IF(start:end=recordLevel, rangeStart:rangeEnd)) | |
| máx. | ="Máx: "&MÁX(SE(início:fim=nível_de_registro, início_do_intervalo:fim_do_intervalo)) | |
| média | ="Média: "&MÉDIASE(início:fim, nível do registro, início do intervalo: fim do intervalo) | |
| soma | ="Soma: "&SOMA.SE(início:fim, nível do registro, início do intervalo: fim do intervalo) | |
date |
contar | ="Contagem: "&CONT.SE(início:fim, recordLevel) |
| mais cedo | ="Mais antigo: "& TEXTO(MIN(SE(início:fim=nível_de_registro, início_do_intervalo:fim_do_intervalo)), formato) | |
| mais recente | ="Último: "&TEXTO(MÁXIMO(SE(início:fim=nível_de_registro, início_do_intervalo:fim_do_intervalo)), formato) |
Known Limitations
| Limitação | Descrição |
|---|---|
| Exportando resumos personalizados | Resumos personalizados serão exportados como strings em vez de funções do Excel. |
| Exportando resumos com modelos | Resumos com modelos não são suportados e serão exportados como os padrões. |
Keyboard Navigation
As linhas de resumo podem ser navegadas com as seguintes interações de teclado:
- UP- navega uma célula para cima
- DOWN- navega uma célula para baixo
- LEFT- navega uma célula à esquerda
- RIGHT- navega uma célula para a direita
- CTRL + LEFT ou HOME- navega para a célula mais à esquerda
- CTRL + RIGHT ou END- navega para a célula mais à direita
Estilização
Para começar a estilizar o comportamento de ordenação, precisamos importar oindex arquivo, onde todas as funções de tema e mixins de componentes estão ativados:
@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
Em vez de codificar os valores de cor como acabamos de fazer, podemos alcançar maior flexibilidade em termos de cores usando aspalette funções e.color Por favor, consulte oPalettes tópico para orientações detalhadas sobre como usá-los.
A última etapa é incluir o tema personalizado do 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
- IgxTreeGridComponent API
- IgxTreeGridComponent Styles
- IgxTreeGridSummaries Styles
- IgxResumoOperando
- IgxNumberSummaryOperand
- IgxDataResumoOperando
- Componente IgxColumnGroup
- IgxColumnComponent
Additional Resources
- Visão geral da grade de árvore
- Tipos de dados de coluna
- Virtualização e desempenho
- Paginação
- Filtragem
- Classificação
- Movimentação de Colunas
- Fixação de coluna
- Redimensionamento de colunas
- Escolha