Angular Descripción general del componente de cuadrícula de datos jerárquicos

    The Ignite UI for Angular Hierarchical Data Grid is used to display and manipulate hierarchical tabular data. Quickly bind your data with very little code or use a variety of events to customize different behaviors. This component provides a rich set of features like data selection, excel style filtering, sorting, paging, templating, column moving, column pinning, export to Excel, CSV and PDF and more. The Hierarchical Grid builds upon the Flat Grid Component and extends its functionality by allowing the users to expand or collapse the rows of the parent grid, revealing corresponding child grids, when more detailed information is needed.

    Angular Hierarchical Data Grid Example

    En este ejemplo de cuadrícula angular, puede ver cómo los usuarios pueden visualizar conjuntos jerárquicos de datos y usar plantillas de celdas para agregar otros componentes visuales como Sparkline.

    Getting Started with Ignite UI for Angular Hierarchical Data Grid

    Nota

    Este componente puede utilizar elHammerModule opcional. Puede importarse en el módulo raíz de la aplicación para que las interacciones táctiles funcionen como se espera.

    Para empezar a utilizar el componente de cuadrícula de datos jerárquicos de Ignite UI for Angular, 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 importarlosIgxHierarchicalGridModule en tu archivo app.module.ts.

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

    Alternativamente,16.0.0 puedes importarlosIgxHierarchicalGridComponent como una dependencia independiente, o usar elIGX_HIERARCHICAL_GRID_DIRECTIVES token para importar el componente y todos sus componentes y directivas de soporte.

    // home.component.ts
    
    import { IGX_HIERARCHICAL_GRID_DIRECTIVES } from 'igniteui-angular/grids/hierarchical-grid';
    // import { IGX_HIERARCHICAL_GRID_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
    
    @Component({
        selector: 'app-home',
        template: `
        <igx-hierarchical-grid #hierarchicalGrid [data]="singers" [autoGenerate]="true">
            <igx-row-island [key]="'Albums'" [autoGenerate]="true">
                <igx-row-island [key]="'Songs'" [autoGenerate]="true">
                </igx-row-island>
            </igx-row-island>
            <igx-row-island [key]="'Tours'" [autoGenerate]="true">
            </igx-row-island>
        </igx-hierarchical-grid>
        `,
        styleUrls: ['home.component.scss'],
        standalone: true,
        imports: [IGX_HIERARCHICAL_GRID_DIRECTIVES]
        /* or imports: [IgxHierarchicalGridComponent, IgxRowIslandComponent] */
    })
    export class HomeComponent {
        public singers: Artist [];
    }
    

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

    Using the Angular Hierarchical Data Grid

    El enlace de datos

    igx-hierarchical-grid derives from igx-grid and shares most of its functionality. The main difference is that it allows multiple levels of hierarchy to be defined. They are configured through a separate tag within the definition of igx-hierarchical-grid, called igx-row-island. The igx-row-island component defines the configuration for each child grid for the particular level. Multiple row islands per level are also supported. The Hierarchical Grid supports two ways of binding to data:

    Uso de datos jerárquicos

    Si la aplicación carga todos los datos jerárquicos como una matriz de objetos que hacen referencia a matrices de objetos secundarios, entonces la cuadrícula jerárquica se puede configurar para leerlos y vincularlos automáticamente. A continuación se muestra un ejemplo de una fuente de datos jerárquica correctamente estructurada:

    export const singers = [{
        "Artist": "Naomí Yepes",
        "Photo": "assets/images/hgrid/naomi.png",
        "Debut": "2011",
        "Grammy Nominations": 6,
        "Grammy Awards": 0,
        "Tours": [{
            "Tour": "Faithful Tour",
            "Started on": "Sep-12",
            "Location": "Worldwide",
            "Headliner": "NO",
            "Toured by": "Naomí Yepes"
        }],
        "Albums": [{
            "Album": "Dream Driven",
            "Launch Date": new Date("August 25, 2014"),
            "Billboard Review": "81",
            "US Billboard 200": "1",
            "Artist": "Naomí Yepes",
            "Songs": [{
                "No.": "1",
                "Title": "Intro",
                "Released": "*",
                "Genre": "*",
                "Album": "Dream Driven"
            }]
        }]
    }];
    

    Each igx-row-island should specify the key of the property that holds the children data.

    <igx-hierarchical-grid #hierarchicalGrid [data]="singers" [autoGenerate]="true">
        <igx-row-island [key]="'Albums'" [autoGenerate]="true">
            <igx-row-island [key]="'Songs'" [autoGenerate]="true">
            </igx-row-island>
        </igx-row-island>
        <igx-row-island [key]="'Tours'" [autoGenerate]="true">
        </igx-row-island>
    </igx-hierarchical-grid>
    
    Nota

    Note that instead of data the user configures only the key that the igx-hierarchical-grid needs to read to set the data automatically.

    Uso de la carga bajo demanda

    Most applications are designed to load as little data as possible initially, which results in faster load times. In such cases igx-hierarchical-grid may be configured to allow user-created services to feed it with data on demand. The following configuration uses a special @Output and a newly introduced loading-in-progress template to provide a fully-featured load-on-demand.

    <!-- hierarchicalGridSample.component.html -->
    
    <igx-hierarchical-grid #hGrid [primaryKey]="'CustomerID'" [autoGenerate]="true" [height]="'600px'" [width]="'100%'">
        <igx-row-island [key]="'Orders'" [primaryKey]="'OrderID'" [autoGenerate]="true"  (gridCreated)="gridCreated($event, 'CustomerID')">
            <igx-row-island [key]="'Order_Details'" [primaryKey]="'ProductID'" [autoGenerate]="true" (gridCreated)="gridCreated($event, 'OrderID')">
            </igx-row-island>
        </igx-row-island>
    </igx-hierarchical-grid>
    
    //  hierarchicalGridSample.component.ts
    
    @Component({...})
    export class HierarchicalGridLoDSampleComponent implements AfterViewInit {
        @ViewChild("hGrid")
        public hGrid: IgxHierarchicalGridComponent;
    
        constructor(private remoteService: RemoteLoDService) { }
    
        public ngAfterViewInit() {
            this.hGrid.isLoading = true;
            this.remoteService.getData({ parentID: null, rootLevel: true, key: "Customers" }).subscribe((data) => {
                this.hGrid.isLoading = false;
                this.hGrid.data = data;
                this.hGrid.cdr.detectChanges();
            });
        }
    
        public gridCreated(event: IGridCreatedEventArgs, _parentKey: string) {
            const dataState = {
                key: event.owner.key,
                parentID: event.parentID,
                parentKey: _parentKey,
                rootLevel: false
            };
            event.grid.isLoading = true;
            this.remoteService.getData(dataState).subscribe(
                (data) => {
                    event.grid.isLoading = false;
                    event.grid.data = data;
                    event.grid.cdr.detectChanges();
                }
            );
        }
    }
    
    // remote-load-on-demand.service.ts
    
    @Injectable()
    export class RemoteLoDService {
        public url = `https://services.odata.org/V4/Northwind/Northwind.svc/`;
    
        constructor(private http: HttpClient) { }
    
        public getData(dataState?: any): Observable<any[]> {
            return this.http.get(this.buildUrl(dataState)).pipe(
                map((response) => response["value"])
            );
        }
    
        public buildUrl(dataState) {
            let qS = "";
            if (dataState) {
                qS += `${dataState.key}?`;
    
                if (!dataState.rootLevel) {
                    if (typeof dataState.parentID === "string") {
                        qS += `$filter=${dataState.parentKey} eq '${dataState.parentID}'`;
                    } else {
                        qS += `$filter=${dataState.parentKey} eq ${dataState.parentID}`;
                    }
                }
            }
            return `${this.url}${qS}`;
        }
    }
    

    Ocultar/Mostrar indicadores de expansión de fila

    Si tienes una forma de proporcionar información sobre si una fila tiene hijos antes de expandirse, podrías usar la propiedad dehasChildrenKey entrada. De este modo, podrías proporcionar una propiedad booleana desde los objetos de datos que indique si debe mostrarse un indicador de expansión.

    <igx-hierarchical-grid #grid [data]="data" primaryKey="ID" hasChildrenKey="hasChildren">
            ...
    </igx-hierarchical-grid>
    

    Ten en cuenta que no es necesario establecer lahasChildrenKey propiedad. En caso de que no lo proporciones, se mostrarán indicadores de expansión para cada fila.

    Además, si desea mostrar/ocultar el indicador de expandir/contraer todo el encabezado, puede utilizar la propiedad showExpandAll. Esta UI está deshabilitada de forma predeterminada por razones de rendimiento y no se recomienda habilitarla en grids con gran cantidad de datos o grids con carga bajo demanda.

    Características

    The grid features could be enabled and configured through the igx-row-island markup - they get applied for every grid that is created for it. Changing options at runtime through the row island instance changes them for each of the grids it has spawned.

    <igx-hierarchical-grid [data]="localData" [autoGenerate]="false"
        [allowFiltering]='true' [height]="'600px'" [width]="'800px'" #hGrid>
        <igx-column field="ID" [pinned]="true" [filterable]='true'></igx-column>
        <igx-column-group header="Information">
            <igx-column field="ChildLevels"></igx-column>
            <igx-column field="ProductName" hasSummary='true'></igx-column>
        </igx-column-group>
        <igx-row-island [key]="'childData'" [autoGenerate]="false" [rowSelection]="'multiple'" #layout1>
            <igx-column field="ID" [hasSummary]='true' [dataType]="'number'"></igx-column>
            <igx-column-group header="Information2">
                <igx-column field="ChildLevels"></igx-column>
                <igx-column field="ProductName"></igx-column>
            </igx-column-group>
            <igx-paginator *igxPaginator [perPage]="5"></igx-paginator>
        </igx-row-island>
        <igx-paginator>
        </igx-paginator>
    </igx-hierarchical-grid>
    

    Las siguientes características de grid funcionan a nivel de grid, lo que significa que cada instancia de grid las administra independientemente del resto de grids:

    • Clasificación
    • Filtración
    • Paginación
    • Encabezados de varias columnas
    • Ocultación
    • Fijar
    • Moviente
    • resúmenes
    • Buscar

    The Selection and Navigation features work globally for the whole igx-hierarchical-grid

    • Selección La selección no permite que las celdas seleccionadas estén presentes en dos cuadrículas secundarias diferentes a la vez.
    • Navegación Al navegar hacia arriba/abajo, si el elemento siguiente/anterior es una cuadrícula secundaria, la navegación continuará en la cuadrícula secundaria relacionada, marcando la celda relacionada como seleccionada y enfocada. Si la celda secundaria está fuera del puerto de visualización visible actual, se desplaza a la vista para que la celda seleccionada siempre esté visible.

    Botón Contraer todo

    La cuadrícula jerárquica permite a los usuarios contraer convenientemente todas las filas actualmente expandidas presionando el botón "Contraer todo" en la esquina superior izquierda. Además, cada cuadrícula secundaria que contiene otras cuadrículas y es una cuadrícula jerárquica en sí misma, también tiene un botón de este tipo; de esta manera, el usuario puede contraer solo una cuadrícula determinada en la jerarquía:

    Icono de colapsar todo

    Dimensionamiento

    Consulte el tema Tamaño de la cuadrícula.

    operaciones CRUD

    Nota

    An important difference from the flat Data Grid is that each instance for a given row island has the same transaction service instance and accumulates the same transaction log. In order to enable the CRUD functionality users should inject the IgxHierarchicalTransactionServiceFactory.

    La llamada a los métodos CRUD API aún se debe realizar a través de cada instancia de grid separada.

    Consulte el tema Cómo crear operaciones CRUD con igxGrid.

    Estilismo

    The igxHierarchicalGrid allows styling through the Ignite UI for Angular Theme Library. The grid's grid-theme exposes a wide variety of properties, which allow the customization of all the features of the grid.

    En los pasos a continuación, veremos los pasos para personalizar el estilo igxHierarchicalGrid.

    Importando tema global

    To begin the customization of the hierarchical grid, you need to import the index file, where all styling functions and mixins are located.

    @use "igniteui-angular/theming" as *;
    
    // IMPORTANT: Prior to Ignite UI for Angular version 13 use:
    // @import '~igniteui-angular/lib/core/styles/themes/index';
    

    Definición de tema personalizado

    Next, create a new theme, that extends the grid-theme and accepts the parameters, required to customize the hierarchical grid as desired.

    Nota

    There is no specific sass hierarchical grid function.

    $custom-theme: grid-theme(
      $cell-active-border-color: #ffcd0f,
      $cell-selected-background: #6f6f6f,
      $row-hover-background: #f8e495,
      $row-selected-background: #8d8d8d,
      $header-background: #494949,
      $header-text-color: #fff,
      $expand-icon-color: #ffcd0f,
      $expand-icon-hover-color: #e0b710,
      $resize-line-color: #ffcd0f,
      $row-highlight: #ffcd0f
    );
    
    Nota

    En lugar de codificar los valores de color como acabamos de hacer, podemos lograr mayor flexibilidad en cuanto a colores usando laspalette funciones ycolor. Por favor, consulta elPalettes tema para obtener una guía detallada sobre cómo utilizarlos.

    Aplicar el tema personalizado

    The easiest way to apply your theme is with a sass @include statement in the global styles file:

    @include css-vars($custom-theme);
    

    In order for the custom theme do affect only specific component, you can move all of the styles you just defined from the global styles file to the custom component's style file (including the import of the index file). This way, due to Angular's ViewEncapsulation, your styles will be applied only to your custom component.

    Manifestación

    Nota

    La muestra no se verá afectada por el tema global seleccionado deChange Theme.

    Rendimiento (Experimental)

    EligxHierarchicalGrid diseño permite aprovechar la función de Fusión de Eventos que Angular ha introducido. Esta función permite mejorar el rendimiento aproximadamente20% en términos de interacciones y capacidad de respuesta. Esta función puede activarse a nivel de aplicación simplemente estableciendo lasngZoneEventCoalescing propiedades yngZoneRunCoalescing entrue elbootstrapModule método:

    platformBrowserDynamic()
      .bootstrapModule(AppModule, { ngZoneEventCoalescing: true, ngZoneRunCoalescing: true })
      .catch(err => console.error(err));
    
    Nota

    This is still in experimental feature for the igxHierarchicalGrid. This means that there might be some unexpected behaviors in the Hierarchical Grid. In case of encountering any such behavior, please contact us on our Github page.

    Nota

    Activarlo puede afectar a otras partes de una Angular aplicación con las que noigxHierarchicalGrid está relacionado.

    Limitaciones conocidas

    Limitación Descripción
    Agrupar por La función Agrupar por no es compatible con la cuadrícula jerárquica.
    Nota

    igxHierarchicalGridusaigxForOf directiva interna, por lo que todasigxForOf las limitaciones son válidas paraigxHierarchicalGrid. Para más detalles, véase la sección de Problemas Conocidos de igxForOf.

    Referencias de API

    Dependencias temáticas

    Recursos adicionales

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