Descripción general del componente de cuadrícula de pivote Angular

    Ignite UI for Angular cuadrícula dinámica es uno de nuestros mejores componentes Angular, ya que representa una tabla de valores agrupados y agregados que le permite organizar y resumir datos en forma de tabla. Es una herramienta de resumen de datos que se utiliza para reorganizar y resumir columnas y filas de datos seleccionadas provenientes de una hoja de cálculo o tabla de base de datos para obtener un informe deseado.

    What is Angular Pivot Grid?

    El componente Angular Pivot Grid presenta datos en una tabla dinámica y ayuda a realizar análisis complejos en el conjunto de datos proporcionado. Este sofisticado control Pivot Grid se utiliza para organizar, resumir y filtrar grandes volúmenes de datos que luego se muestran en un formato de tabla cruzada. Las características clave de Angular Pivot Grid son las dimensiones de fila, las dimensiones de columna, las agregaciones y los 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

    El siguiente es un ejemplo Angular Pivot Grid en combinación con el componente de selector de datos Angular Pivot. De esta manera, puede tener opciones de configuración de tiempo de ejecución más flexibles.

    Getting started with Ignite UI for Angular Pivot Grid

    Para empezar a utilizar el componente Ignite UI for Angular Pivot Grid, primero debe instalar Ignite UI for Angular. En una aplicación Angular existente, escriba el siguiente comando:

    ng add igniteui-angular
    

    Para obtener una introducción completa al Ignite UI for Angular, lea el tema de introducción.

    El siguiente paso es importarlosIgxPivotGridModule en tu archivo 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 puedes importarlosIgxPivotGridComponent como una dependencia independiente, o usar elIGX_PIVOT_GRID_DIRECTIVES token para importar el componente y todos sus componentes y directivas de soporte.

    // 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.

    Se pueden definir varias dimensiones hermanas, lo que crea un grupo anidado más complejo en el área de dimensión de fila o columna relacionada.

    Las dimensiones se pueden reordenar o mover de un área a otra mediante sus correspondientes chips mediante arrastrar y 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 de la cuadrícula dinámica, se exponen algunas dimensiones predefinidas adicionales para facilitar la configuración:

    • IgxPivotDateDimension Can be used for date fields. Describes the following hierarchy by default:
      • Todos los periodos
      • Años
      • Cuarteles
      • Meses
      • Fecha completa

    Se puede configurar para filas o columnas, por ejemplo:

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

    También permite una mayor personalización a través del segundo parámetro de opción para habilitar o deshabilitar una parte particular de la jerarquía, por ejemplo:

     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.

    Fuera de la caja, hay 4 agregaciones predefinidas que se pueden utilizar en función del tipo de datos del campo de datos:

    • IgxPivotNumericAggregate- para campos numéricos. Contiene las siguientes funciones de agregación:SUM,AVG,MIN,MAX,.COUNT
    • IgxPivotDateAggregate- para los campos de fecha. Contiene las siguientes funciones de agregación:LATEST,EARLIEST,COUNT.
    • IgxPivotTimeAggregate- para campos temporales. Contiene las siguientes funciones de agregación:LATEST,EARLIEST,COUNT.
    • IgxPivotAggregate- para cualquier otro tipo de datos. Esta es la agregación base. Contiene las siguientes funciones de agregación: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

    Echemos un vistazo a una configuración de pivote básica:

          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
                }
            ]
        };
    

    Esta configuración define 1 fila, 1 columna y 1 agregación que suma los valores de cada grupo de dimensiones. Los miembros coinciden con los campos disponibles en la fuente de datos proporcionada:

    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'
        },
        //...
    ];
    
    

    El resultado es la siguiente vista, que agrupa las columnas únicas de Categorías de productos, los nombres de los vendedores en filas únicas y muestra las agregaciones relacionadas para el número de unidades en las celdas relacionadas:

    Y si quieres agilizar todo el proceso de desarrollo de aplicaciones, puedes probar nuestra App Builder ™WYSIWYG para tu próxima aplicación 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.
      • Se agrega a la colección de valores y se habilita de forma predeterminada.
    • Campos no numéricos:

      • Created as IPivotDimension.
      • Deshabilitado de forma predeterminada.
      • Se ha agregado a la colección de columnas.
    • Campos de fecha (solo el primerdate campo está habilitado, los otrosdate campos aplican la regla de campos no numéricos):

      • Created as IgxPivotDateDimension
      • Habilitado de forma predeterminada
      • agregado a la colección rows.

    Esta función permite a los desarrolladores crear rápidamente una vista dinámica sin especificar manualmente las dimensiones y los valores. Con un selector de pivote junto a la cuadrícula dinámica, los usuarios pueden habilitar y reordenar dimensiones y valores según sea necesario.

    Known Issues and Limitations

    Limitación Descripción
    No se admite la configuración de columnas de forma declarativa. La cuadrícula Pivot genera sus columnas en función de lacolumns configuración, por lo que no se admite configurarlos de forma declarativa, como en la cuadrícula base. Estas columnas no se tienen en cuenta.
    Configuración duplicadamemberName omember valores de propiedad para dimensiones/valores. memberName/member debe ser único para cada dimensión/valor. La duplicación puede provocar la pérdida de datos del resultado final.
    La selección de filas solo se admite ensingle modo. Actualmente no se admite la selección múltiple.
    Fusionar los miembros de la dimensión distingue entre mayúsculas y minúsculas La cuadrícula dinámica crea grupos y fusiona los mismos valores (distingue entre mayúsculas y minúsculas). Pero las dimensiones proporcionanmemberFunction y esto se puede cambiar allí, el resultado de lamemberFunction se comparan y se utilizan como valor de visualización.

    API References

    Additional Resources

    Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.