Visão geral do componente Angular Pivot Grid

    Ignite UI for Angular Pivot Grid é um dos nossos melhores Angular Components, representando uma tabela de valores agrupados e agregados que permite organizar e resumir dados em um formato tabular. É uma ferramenta de sumarização de dados usada para reorganizar e resumir colunas e linhas selecionadas de dados provenientes de uma planilha ou tabela de banco de dados para obter um relatório desejado.

    What is Angular Pivot Grid?

    O componente Angular Pivot Grid apresenta dados em uma tabela dinâmica e ajuda a executar análises complexas no conjunto de dados fornecido. Este sofisticado controle Pivot Grid é usado para organizar, resumir e filtrar grandes volumes de dados que são posteriormente exibidos em um formato de tabela cruzada. Os principais recursos de um Angular Pivot Grid são dimensões de linha, dimensões de coluna, agregações e filtros.

    The IgxPivotGridComponent gives the ability to users to configure and display their data in a multi-dimensional pivot table structure. The rows and columns represent distinct data groups, and the data cell values represent aggregations. This allows complex data analysis based on a simple flat data set. The IgxPivotGridComponent is a feature-rich pivot table that provides easy configuration of the different dimensions and values as well as additional data operations on them like filtering and sorting.

    Angular Pivot Grid Example

    O seguinte é um exemplo de Angular Pivot Grid em combinação com o Angular Pivot Data Selector Component. Dessa forma, você pode ter opções de configuração de tempo de execução mais flexíveis.

    Getting started with Ignite UI for Angular Pivot Grid

    Para começar a usar o componente Ignite UI for Angular Pivot Grid, primeiro você precisa instalar Ignite UI for Angular. Em um aplicativo Angular existente, digite o seguinte comando:

    ng add igniteui-angular
    

    Para obter uma introdução completa ao Ignite UI for Angular, leia o tópico de introdução.

    O próximo passo é importar issoIgxPivotGridModule no seu arquivo app.module.ts.

    // app.module.ts
    
    import { IgxPivotGridModule } from 'igniteui-angular/grids/pivot-grid';
    // import { IgxPivotGridModule } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
        imports: [
            ...
            IgxPivotGridModule,
            ...
        ]
    })
    export class AppModule {}
    

    Alternativamente,16.0.0 você pode importarIgxPivotGridComponent como uma dependência independente ou usar oIGX_PIVOT_GRID_DIRECTIVES token para importar o componente e todos os seus componentes e diretivas de suporte.

    // home.component.ts
    
    import { IGX_PIVOT_GRID_DIRECTIVES } from 'igniteui-angular/grids/pivot-grid';
    // import { IGX_PIVOT_GRID_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-pivot-grid [data]="data" [pivotConfiguration]="pivotConfigHierarchy">
        </igx-pivot-grid>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IGX_PIVOT_GRID_DIRECTIVES]
        /* or imports: [IgxPivotGridComponent] */
    })
    export class HomeComponent {
        public data: Transaction [];
    }
    

    Now that you have the Ignite UI for Angular Pivot Grid module or directives imported, you can start using the igx-pivot-grid component.

    Using the Angular Pivot Grid

    The Angular Pivot Grid Component can be configured via the pivotConfiguration property.

    <igx-pivot-grid #grid1 [data]="data" [pivotConfiguration]="pivotConfigHierarchy">
    </igx-pivot-grid>
    

    It is defined by three main dimensions: rows, columns and values. The rows and columns define the grouped structure that is displayed in the rows and columns of the Angular grid. The values define the aggregation fields and the aggregation that will be used to calculate and display the related values of the groups.

    A filter can also be defined via the filters configuration property. It can be used for fields that you do not want to add as a dimension or a value but would like to filter their related member values via the UI.

    Dimensions configuration

    Each basic dimension configuration requires a memberName that matches a field from the provided data, or a memberFunction that extracts a value from the record in case of complex objects or other custom scenarios.

    Note

    The memberName needs to be unique. In case you need different dimensions for the same field, you can define a custom unique memberName for each, and extract the related value via memberFunction.

    Várias dimensões irmãs podem ser definidas, o que cria um grupo aninhado mais complexo na área de dimensão de linha ou coluna relacionada.

    As dimensões podem ser reordenadas ou movidas de uma área para outra através de seus chips correspondentes usando arrastar e soltar.

    A dimension can also describe an expandable hierarchy via the childLevel property, for example:

       {
                memberFunction: () => 'All',
                memberName: 'AllProducts',
                enabled: true,
                childLevel: {
                    memberFunction: (data) => data.ProductCategory,
                    memberName: 'ProductCategory',
                    enabled: true
                }
        }
    
    

    In this case the dimension renders an expander in the related section of the grid (row or column) and allows the children to be expanded or collapsed as part of the hierarchy. By default the row dimensions are initially expanded. This behavior can be controlled with the defaultExpandState @Input of the pivot grid.

    Predefined dimensions

    Como parte da grade dinâmica, algumas dimensões predefinidas adicionais são expostas para facilitar a configuração:

    • IgxPivotDateDimension Can be used for date fields. Describes the following hierarchy by default:
      • Todos os períodos
      • Anos
      • Quartos
      • Meses
      • Data completa

    Ele pode ser definido para linhas ou colunas, por exemplo:

    public pivotConfigHierarchy: IPivotConfiguration = {
        rows: [
            new IgxPivotDateDimension({ memberName: 'Date', enabled: true });
        ]
    }
    

    Ele também permite uma personalização adicional por meio do segundo parâmetro de opção para habilitar ou desabilitar uma parte específica da hierarquia, por exemplo:

     new IgxPivotDateDimension({ memberName: 'Date', enabled: true }, {
        total: true,
        years: true,
        months: true,
        fullDate: true,
        quarters: false
    });
    

    Values configuration

    A value configuration requires a member that matches a field from the provided data, or it can define either via an aggregatorName or custom aggregator function for more complex scenarios.

    Note

    The member needs to be unique. In case you need different value aggregations for the same field, you can define a custom unique member for each, and extract the related value via the aggregator function.

    Fora da caixa, existem 4 agregações predefinidas que podem ser usadas dependendo do tipo de dados do campo de dados:

    • IgxPivotNumericAggregate - for numeric fields. Contains the following aggregation functions: SUM, AVG, MIN, MAX, COUNT.
    • IgxPivotDateAggregate - for date fields. Contains the following aggregation functions: LATEST, EARLIEST, COUNT.
    • IgxPivotTimeAggregate - for time fields. Contains the following aggregation functions: LATEST, EARLIEST, COUNT.
    • IgxPivotAggregate - for any other data types. This is the base aggregation. Contains the following aggregation functions: COUNT.

    The current aggregation function can be changed at runtime using the value chip's drop-down. By default, it displays a list of available aggregations based on the field's data type. A custom list of aggregations can also be set via the aggregateList property, for example:

    public pivotConfigHierarchy: IPivotConfiguration = {
        values: [
            {
                member: 'AmountOfSale',
                displayName: 'Amount of Sale',
                aggregate: {
                    key: 'SUM',
                    aggregator: IgxTotalSaleAggregate.totalSale,
                    label: 'Sum of Sale'
                },
                aggregateList: [{
                    key: 'SUM',
                    aggregator: IgxTotalSaleAggregate.totalSale,
                    label: 'Sum of Sale'
                }, {
                    key: 'MIN',
                    aggregator: IgxTotalSaleAggregate.totalMin,
                    label: 'Minimum of Sale'
                }, {
                    key: 'MAX',
                    aggregator: IgxTotalSaleAggregate.totalMax,
                    label: 'Maximum of Sale'
                }]
            }
        ]
    }
    
    public static totalSale: PivotAggregation = (members, data: any) =>
        data.reduce((accumulator, value) => accumulator + value.UnitPrice * value.UnitsSold, 0);
    
    public static totalMin: PivotAggregation = (members, data: any) => {
        return data.map(x => x.UnitPrice * x.UnitsSold).reduce((a, b) => Math.min(a, b));
    };
    
    public static totalMax: PivotAggregation = (members, data: any) => {
        return data.map(x => x.UnitPrice * x.UnitsSold).reduce((a, b) => Math.max(a,b));
    };
    

    The pivot value also provides a displayName property. It can be used to display a custom name for this value in the column header.

    Note

    If you define both aggregatorName and aggregator function, aggregatorName takes precedence. If none is set then an error is thrown.

    Enable property

    IPivotConfiguration is the interface that describes the current state of the IgxPivotGrid component. With it the developer can declare fields of the data as rows, columns, filters or values. The configuration allows enabling or disabling each of these elements separately. Only enabled elements are included in the current state of the pivot grid. The IgxPivotDataSelector component utilizes the same configuration and shows a list of all elements - enabled and disabled. For each of them there is a checkbox in the appropriate state. End-users can easily tweak the pivot state by toggling the different elements using these checkboxes. The enable property controls if a given IPivotDimension or IPivotValue is active and takes part in the pivot view rendered by the pivot grid.

    Full configuration example

    Vamos dar uma olhada em uma configuração básica de pivô:

          public pivotConfigHierarchy: IPivotConfiguration = {
            columns: [
                {
    
                    memberName: 'Product',
                    memberFunction: (data) => data.Product.Name,
                    enabled: true
                }
    
            ],
            rows: [
                {
                    memberName: 'Seller',
                    memberFunction: (data) => data.Seller.Name,
                    enabled: true,
                }
            ],
            values: [
                {
                    member: 'NumberOfUnits',
                    aggregate: {
                        aggregator: IgxPivotNumericAggregate.sum,
                        key: 'sum',
                        label: 'Sum'
                    },
                    enabled: true
                },
                {
                    member: 'AmountOfSale',
                    aggregate: {
                        aggregatorName: 'SUM',
                        key: 'sum',
                        label: 'Sum'
                    },
                    enabled: true
                }
            ]
        };
    

    Essa configuração define 1 linha, 1 coluna e 1 agregação que soma os valores de cada grupo de dimensões. Os campos de correspondência de membros disponíveis na fonte de dados fornecida:

    public data = [
    [
        {
            Product: {
                Name: 'Clothing',
                UnitPrice: '12.814860936633712'
            },
            Seller: {
                Name: 'Stanley Brooker',
                City: 'Seattle'
            },
            Date: '2007-01-01T00:00:00',
            Value: '94.2652032683907',
            NumberOfUnits: '282'
        },
        //...
    ];
    
    

    Resultando na seguinte visualização, que agrupa as colunas exclusivas Categorias de produtos, Nomes de vendedores em linhas exclusivas e exibe as agregações relacionadas para o número de unidades nas células relacionadas:

    E se você quiser agilizar todo o processo de desenvolvimento de aplicativos, experimente nosso WYSIWYG App Builder ™ para seu próximo aplicativo Angular.

    Auto generate configuration

    The autoGenerateConfig property automatically generates dimensions and values based on the data source fields:

    • Campos numéricos:

      • Created as IPivotValue using IgxPivotNumericAggregate.sum aggregator.
      • Adicionado à coleção de valores e habilitado por padrão.
    • Campos não numéricos:

      • Created as IPivotDimension.
      • Desabilitado por padrão.
      • Adicionado à coleção columns.
    • Date Fields(only the first date field is enabled, the other date fields apply non-numeric fields rule):

      • Created as IgxPivotDateDimension
      • Habilitado por padrão
      • adicionado à coleção rows.

    Esse recurso permite que os desenvolvedores criem rapidamente uma visualização dinâmica sem especificar manualmente dimensões e valores. Com um seletor dinâmico ao lado da grade dinâmica, os usuários podem ativar e reordenar dimensões e valores conforme necessário.

    Known Issues and Limitations

    Limitação Descrição
    Não há suporte para a configuração de colunas declarativamente. A grade Pivot gera suas colunas com base nocolumns configuração, então defini-las declarativamente, como na grade base, não é suportado. Tais colunas são desconsideradas.
    Definir valores duplicadosmemberName oumember de propriedade para dimensões/valores. memberName/member deve ser único para cada dimensão/valor. Duplicação pode resultar em perda de dados do resultado final.
    A seleção de linha só é suportada emsingle modo. No momento, não há suporte para seleção múltipla.
    A fusão dos membros da dimensão diferencia maiúsculas de minúsculas A grade dinâmica cria grupos e mescla os mesmos valores (sensíveis a maiúsculas e minúsculas). Mas as dimensões fornecemmemberFunction e isso pode ser alterado aí, o resultado domemberFunction são comparados e usados como valor de exibição.

    API References

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.