Descripción general del componente de cuadrícula de árbol Angular
The Ignite UI for Angular Tree Grid is used to display and manipulate hierarchical or flat self-referencing 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, grouping, templating, column moving, column pinning, export to Excel, CSV and PDF, and more.
Angular Ejemplo de cuadrícula de árbol
In this example, you can see how users can display hierarchical data. We have included filtering and sorting options, pinning and hiding, row selection, export to excel, csv and pdf, and cell templating that uses our Sparkline component. In addition, you can see an example of custom pagination with Angular Pagination.
Empezando con Ignite UI for Angular Tree Grid
Para comenzar con el componente Ignite UI for Angular Tree 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 importarlosIgxTreeGridModule en tu archivo app.module.ts.
// app.module.ts
import { IgxTreeGridModule } from 'igniteui-angular/grids/tree-grid';
// import { IgxTreeGridModule } from '@infragistics/igniteui-angular'; for licensed package
@NgModule({
imports: [
...
IgxTreeGridModule,
...
]
})
export class AppModule {}
Alternativamente,16.0.0 puedes importarlosIgxTreeGridComponent como una dependencia independiente, o usar elIGX_TREE_GRID_DIRECTIVES token para importar el componente y todos sus componentes y directivas de soporte.
// home.component.ts
import { IGX_TREE_GRID_DIRECTIVES } from 'igniteui-angular/grids/tree-grid';
// import { IGX_TREE_GRID_DIRECTIVES } from '@infragistics/igniteui-angular'; for licensed package
@Component({
selector: 'app-home',
template: '<igx-tree-grid [data]="data"></igx-tree-grid>',
styleUrls: ['home.component.scss'],
standalone: true,
imports: [IGX_TREE_GRID_DIRECTIVES]
/* or imports: [IgxTreeGridComponent] */
})
export class HomeComponent {
public data: Employee [];
}
Now that you have the Ignite UI for Angular Tree Grid module or directives imported, you can start using the igx-tree-grid component.
Uso de la cuadrícula de árbol Angular
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.
The IgxTreeGridComponent shares a lot of features with the IgxGridComponent, but it also adds the ability to display its data hierarchically.
In order to achieve this, the IgxTreeGridComponent provides us with a couple of ways to define the relations among our data objects - by using a child collection for every data object or by using primary and foreign keys for every data object.
Células de árbol
Independientemente de qué opción se utilice para construir la jerarquía de la cuadrícula de árbol (colección secundaria o claves primarias y externas), las filas de la cuadrícula de árbol se construyen con dos tipos de celdas:
IgxGridCell- Ordinary cell that contains a value.IgxGridCell- Tree cell that contains a value, an expand/collapse indicator and an indentation div element, which is based on the level of the cell's row. The level of a row component can be accessed through thelevelproperty of its innertreeRow.
Nota
Cada fila puede tener solo una celda de árbol, pero puede tener múltiples (o ninguna) celdas ordinarias.
Profundidad inicial de expansión
Initially the tree grid will expand all node levels and show them. This behavior can be configured using the expansionDepth property. By default its value is Infinity which means all node levels will be expanded. You may control the initial expansion depth by setting this property to a numeric value. For example 0 will show only root level nodes, 1 will show root level nodes and their child nodes and so on.
Colección infantil
When we are using the child collection option, every data object contains a child collection, that is populated with items of the same type as the parent data object. This way every record in our tree grid will have a direct reference to any of its children. In this case the data property of our tree grid that contains the original data source will be a hierarchically defined collection.
Para este ejemplo, usemos la siguiente estructura de colección:
// Sample Employee Data
export const EMPLOYEE_DATA = [
{
Name: "Johnathan Winchester",
ID: 1,
HireDate: new Date(2008, 3, 20),
Age: 55,
Employees: [
{
Name: "Michael Burke",
ID: 3,
HireDate: new Date(2011, 6, 3),
Age: 43,
Employees: []
},
{
Name: "Thomas Anderson"
ID: 2,
HireDate: new Date(2009, 6, 19),
Age: 29,
Employees: []
},
...
]
},
...
]
Now let's start by importing our data collection and binding it to the data input of our tree grid.
<!--treeGridSample.component.html-->
<igx-tree-grid #treeGrid [data]="localData">
</igx-tree-grid>
In order for the IgxTreeGridComponent to build the hierarchy, we will have to set its childDataKey property to the name of the child collection that is used in each of our data objects. In our case that will be the Employees collection.
In addition, we will disable the automatic column generation and define them manually by matching them to the actual properties of our data objects. (The Employees collection will be automatically used for the hierarchy, so there is no need to include it in the columns' definitions.)
<!--treeGridSample.component.html-->
<igx-tree-grid #treeGrid [data]="localData" childDataKey="Employees"
[autoGenerate]="false">
<igx-column field="Name" dataType="string"></igx-column>
<igx-column field="HireDate" dataType="date"></igx-column>
<igx-column field="Age" dataType="number"></igx-column>
</igx-tree-grid>
We will now enable the row selection and paging features of the tree grid by using the rowSelection and the paging properties.
We will also enable the summaries feature on the first column and the filtering, sorting, editing, moving and resizing features for each of our columns.
<!--treeGridSample.component.html-->
<igx-tree-grid #treeGrid [data]="localData" childDataKey="Employees"
[autoGenerate]="false" [rowSelection]="'multiple'" [allowFiltering]="true" [moving]="true">
<igx-column field="Name" dataType="string" [sortable]="true" [editable]="true" [resizable]="true"
[hasSummary]="true"></igx-column>
<igx-column field="HireDate" dataType="date" [sortable]="true" [editable]="true" [resizable]="true"></igx-column>
<igx-column field="Age" dataType="number" [sortable]="true" [editable]="true" [resizable]="true"></igx-column>
<igx-paginator>
</igx-paginator>
</igx-tree-grid>
Finally, we will enable the toolbar of our tree grid, along with the column hiding, column pinning and exporting features by using the IgxGridToolbarComponent, IgxGridToolbarHidingComponent, IgxGridToolbarPinningComponent and IgxGridToolbarExporterComponent respectively.
<!--treeGridSample.component.html-->
<igx-tree-grid #treeGrid [data]="localData" childDataKey="Employees"
[autoGenerate]="false" [rowSelection]="'multiple'" [allowFiltering]="true" [moving]="true">
<igx-grid-toolbar>
<igx-grid-toolbar-title>Employees</igx-grid-toolbar-title>
<igx-grid-toolbar-actions>
<igx-grid-toolbar-hiding></igx-grid-toolbar-hiding>
<igx-grid-toolbar-pinning></igx-grid-toolbar-pinning>
<igx-grid-toolbar-exporter></igx-grid-toolbar-exporter>
</igx-grid-toolbar-actions>
</igx-grid-toolbar>
<igx-column field="Name" dataType="string" [sortable]="true" [editable]="true" [resizable]="true"></igx-column>
<igx-column field="HireDate" dataType="date" [sortable]="true" [editable]="true" [resizable]="true"></igx-column>
<igx-column field="Age" dataType="number" [sortable]="true" [editable]="true" [resizable]="true"></igx-column>
<igx-paginator [perPage]="6">
</igx-paginator>
</igx-tree-grid>
Puedes ver el resultado del código anterior al comienzo de este artículo en la sección Ejemplo de cuadrícula de árbol Angular.
Claves primarias y extranjeras
When we are using the primary and foreign keys option, every data object contains a primary key and a foreign key. The primary key is the unique identifier of the current data object and the foreign key is the unique identifier of its parent. In this case the data property of our tree grid that contains the original data source will be a flat collection.
El siguiente es un ejemplo de un componente que contiene una colección plana definida con una relación de claves primarias y externas:
// treeGridSample.component.ts
@Component({...})
export class MyComponent implements OnInit {
public data: any[];
constructor() { }
public ngOnInit() {
// Primary and Foreign keys sample data
this.data = [
{ ID: 1, ParentID: -1, Name: "Casey Houston", JobTitle: "Vice President", Age: 32 },
{ ID: 2, ParentID: 1, Name: "Gilberto Todd", JobTitle: "Director", Age: 41 },
{ ID: 3, ParentID: 2, Name: "Tanya Bennett", JobTitle: "Director", Age: 29 },
{ ID: 4, ParentID: 2, Name: "Jack Simon", JobTitle: "Software Developer", Age: 33 },
{ ID: 5, ParentID: 8, Name: "Celia Martinez", JobTitle: "Senior Software Developer", Age: 44 },
{ ID: 6, ParentID: -1, Name: "Erma Walsh", JobTitle: "CEO", Age: 52 },
{ ID: 7, ParentID: 2, Name: "Debra Morton", JobTitle: "Associate Software Developer", Age: 35 },
{ ID: 8, ParentID: 10, Name: "Erika Wells", JobTitle: "Software Development Team Lead", Age: 50 },
{ ID: 9, ParentID: 8, Name: "Leslie Hansen", JobTitle: "Associate Software Developer", Age: 28 },
{ ID: 10, ParentID: -1, Name: "Eduardo Ramirez", JobTitle: "Development Manager", Age: 53 }
];
}
}
En los datos de ejemplo anteriores, todos los registros tienen un ID, un ParentID y algunas propiedades adicionales como Nombre, Título del trabajo y Edad. Como se mencionó anteriormente, el ID de los registros debe ser único. ParentID contiene el ID del nodo principal. Si una fila tiene un ParentID que no coincide con ninguna fila en la cuadrícula de árbol, eso significa que esta fila es una fila raíz.
The parent-child relation is configured using the tree grid's primaryKey and foreignKey properties.
Aquí está la plantilla del componente que demuestra cómo configurar la cuadrícula de árbol para mostrar los datos definidos en la colección plana anterior:
<!--treeGridSample.component.html-->
<igx-tree-grid #treeGrid [data]="data" primaryKey="ID" foreignKey="ParentID"
[autoGenerate]="false">
<igx-column field="Name" dataType="string"></igx-column>
<igx-column field="JobTitle" dataType="string"></igx-column>
<igx-column field="Age" dataType="number"></igx-column>
</igx-tree-grid>
In addition we will enable the row selection feature of the tree grid by using the rowSelection property and also the filtering, sorting, editing, moving and resizing features for each of our columns.
<!--treeGridSample.component.html-->
<igx-tree-grid #treeGrid [data]="data" primaryKey="ID" foreignKey="ParentID"
[autoGenerate]="false" [rowSelection]="'multiple'" [allowFiltering]="true" [moving]="true">
<igx-column field="Name" dataType="string" [sortable]="true" [editable]="true" [resizable]="true"></igx-column>
<igx-column field="JobTitle" dataType="string" [sortable]="true" [editable]="true" [resizable]="true"></igx-column>
<igx-column field="Age" dataType="number" [sortable]="true" [editable]="true" [resizable]="true"></igx-column>
</igx-tree-grid>
Y aquí está el resultado final:
Persistencia e integración
La sangría de las celdas del árbol persiste en otras funciones de la cuadrícula del árbol, como el filtrado, la clasificación y la paginación.
- Cuando se aplica la clasificación en una columna, las filas de datos se ordenan por niveles. Esto significa que las filas del nivel raíz se ordenarán independientemente de sus respectivos hijos. Sus respectivas colecciones infantiles también se clasificarán de forma independiente y así sucesivamente.
- The first column (the one that has a
visibleIndexof 0) is always the tree column. - The column that ends up with a
visibleIndexof 0 after operations like column pinning, column hiding and column moving becomes the tree column. - Las hojas de cálculo de Excel exportadas reflejan la jerarquía agrupando los registros tal como están agrupados en la propia cuadrícula de árbol. Todos los estados expandidos de los registros también se conservarán y reflejarán.
- Al exportar a CSV, los niveles y los estados expandidos se ignoran y todos los datos se exportan como planos.
Angular Dimensionamiento de la cuadrícula de árbol
Consulte el tema Tamaño de la cuadrícula.
Estilismo
The Tree Grid allows styling through the Ignite UI for Angular Theme Library. The tree grid's grid-theme exposes a wide variety of properties, which allows the customization of all the tree grid's features.
To get started with styling the Tree Grid, 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-theme and accepts the parameters, required to customize the tree grid as desired.
Nota
There is no specific sass tree 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.
El último paso es incluir el tema del componente en nuestra aplicación.
@include css-vars($custom-theme);
Angular Demo de estilo de cuadrícula en árbol
Nota
La muestra no se verá afectada por el tema global seleccionado deChange Theme.
Rendimiento (Experimental)
EligxTreeGrid 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 igxTreeGrid. This means that there might be some unexpected behaviors in the Tree 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 noigxTreeGrid está relacionado.
Limitaciones conocidas
| Limitación | Descripción |
|---|---|
| Plantillas de celdas de árbol | Al crear una plantilla de celda de árbol, el contenido que se extiende fuera de los límites de la celda no se mostrará a menos que se coloque en una superposición. |
| Agrupar por | La función Agrupar por no es compatible porque es inherente a la cuadrícula de árbol. |
Nota
La arboleda tiene un límite de profundidad de 25 niveles. Para admitir más niveles es necesario agregar clases CSS personalizadas en la aplicación. Puede ver un ejemplo de dicha clase CSS a continuación:
.igx-grid__tree-cell--padding-level-26 {
padding-left: 39rem;
}
Nota
igxTreeGridusaigxForOf directiva interna, por lo que todasigxForOf las limitaciones son válidas paraigxTreeGrid. Para más detalles, véase la sección de Problemas Conocidos de igxForOf.
Referencias de API
- Componente IgxTreeGrid
- IgxGridCell
- IgxÁrbolCuadrículaFila
- Componente IgxGrid
- Estilos de componentes IgxGrid
- Servicio de transacciones IgxBase
Dependencias temáticas
- Tema IgxIcon
- Tema IgxInputGroup
- Tema IgxChip
- Tema IgxRipple
- Tema IgxButton
- Tema IgxOverlay
- Tema desplegable Igx
- Tema IgxCalendario
- Tema IgxSnackBar
- Tema IgxBadge