Descripción general y configuración de la cuadrícula de árbol de Web Components
La cuadrícula de árbol Web Components es un componente de interfaz de usuario que combina la funcionalidad de una cuadrícula de datos (tabla) con una vista de árbol, lo que permite que los datos jerárquicos se muestren fácilmente en un formato tabular. A diferencia de una cuadrícula normal, una cuadrícula de árbol permite que las filas se expandan y contraigan, revelando filas secundarias anidadas debajo de filas principales, lo que la hace útil para representar datos estructurados como exploradores de archivos, organigramas, tareas de proyectos o categorías de productos.
La cuadrícula de árbol Ignite UI for Web Components se utiliza para visualizar y manipular datos jerárquicos o planos con facilidad. Vincule rápidamente sus datos con muy poco código o utilice una variedad de eventos para personalizar diferentes comportamientos. Este componente proporciona un amplio conjunto de funciones como selección de datos, filtrado de estilo Excel, ordenación, paginación, creación de plantillas y movimiento de columnas. La visualización de datos tabulares nunca ha sido tan fácil y atractiva gracias a la cuadrícula de árbol de la interfaz de usuario basada en Material Table.
Web Components Tree Grid Example
En este ejemplo, puede ver cómo los usuarios pueden manipular datos jerárquicos o planos. Hemos incluido opciones de filtrado y clasificación, fijación y ocultación, selección de filas, exportación a Excel y CSV.
Example
Getting Started with Ignite UI for Web Components Tree Grid
Dependencies
Comenzar con nuestra biblioteca Web Components Grid y Web Components Tree Grid en particular es el primer paso para crear aplicaciones potentes y ricas en datos que muestren información jerárquica de una manera clara e interactiva. La cuadrícula de árbol Web Components le permite presentar estructuras de datos primarios y secundarios en un formato tabular familiar, completo con características como expansión de filas, ordenación, filtrado, edición y virtualización para un alto rendimiento con conjuntos de datos grandes.
To get started with the Web Components tree grid, first you need to install the igniteui-webcomponents-grids package.
npm install --save igniteui-webcomponents-grids
También debe incluir la siguiente importación para utilizar la cuadrícula de árbol:
import 'igniteui-webcomponents-grids/grids/combined';
También se debe hacer referencia a los estilos correspondientes. Puede elegir la opción clara u oscura para uno de los temas y, según la configuración de su proyecto, importarlo:
import 'igniteui-webcomponents-grids/grids/themes/light/bootstrap.css';
O para vincularlo:
<link rel='stylesheet' href='node_modules/igniteui-webcomponents-grids/grids/themes/light/bootstrap.css'>
Para obtener más detalles sobre cómo personalizar la apariencia de la cuadrícula de árbol, puede consultar la sección de estilo.
Usage
La cuadrícula de árbol comparte muchas características con la cuadrícula, pero también agrega la capacidad de mostrar sus datos jerárquicamente. Para lograr esto, la cuadrícula de árbol nos proporciona un par de formas de definir las relaciones entre nuestros objetos de datos: usando una colección secundaria para cada objeto de datos o usando claves primarias y externas para cada objeto de datos.
Tree Cells
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:
GridCell- Ordinary cell that contains a value.TreeGridCell- 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.
[!Note] Each row can have only one tree cell, but it can have multiple (or none) ordinary cells.
Initial Expansion Depth
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.
Child Collection
Cuando usamos la opción de colección secundaria, cada objeto de datos contiene una colección secundaria, que se rellena con elementos del mismo tipo que el objeto de datos principal. De esta manera, cada registro en la cuadrícula de árbol tendrá una referencia directa a cualquiera de sus hijos. En este caso, la propiedad de datos de nuestra cuadrícula de árbol que contiene la fuente de datos original será una colección definida jerárquicamente.
Para este ejemplo, usemos la siguiente estructura de colección:
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 our tree grid.
<igc-tree-grid auto-generate="false" id="treeGrid" name="treeGrid">
<igc-column field="name" header="Name" data-type="string"></igc-column>
<igc-column field="hireDate" header="Hire Date" data-type="date"></igc-column>
<igc-column field="age" header="Age" data-type="number"></igc-column>
</igc-tree-grid>
constructor() {
var treeGrid = document.getElementById('treeGrid') as IgcTreeGridComponent;
treeGrid.childDataKey = "Employees";
treeGrid.data = this.employeesNestedData;
}
In order for the tree grid 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 can 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.)
We can now enable the row selection and paging features of the tree grid by using the rowSelection and add the IgcPaginatorComponent element.
We can also enable the summaries, the filtering, sorting, editing, moving and resizing features for each of our columns.
<igc-tree-grid auto-generate="false" id="treeGrid" child-data-key="Employees" row-selection="multiple" allow-filtering="true" moving="true">
<igc-column field="name" header="Name" data-type="string" sortable="true" resizable="true" has-summary="true" editable="true"></igc-column>
<igc-column field="hireDate" header="Hire Date" data-type="date" sortable="true" resizable="true" has-summary="true" editable="true"></igc-column>
<igc-column field="age" header="Age" data-type="number" sortable="true" resizable="true" has-summary="true" editable="true"></igc-column>
<igc-paginator></igc-paginator>
</igc-tree-grid>
Finally, we can enable the toolbar of our tree grid, along with the column hiding, column pinning and exporting features by using the IgcGridToolbarComponent, IgcGridToolbarHidingComponent, IgcGridToolbarPinningComponent and IgcGridToolbarExporterComponent respectively.
<igc-tree-grid auto-generate="false" id="treeGrid" name="treeGrid" child-data-key="Employees" row-selection="multiple" allow-filtering="true" moving="true">
<igc-column field="name" header="Name" data-type="string" sortable="true" resizable="true" has-summary="true" editable="true"></igc-column>
<igc-column field="hireDate" header="Hire Date" data-type="date" sortable="true" resizable="true" editable="true"></igc-column>
<igc-column field="age" header="Age" data-type="number" sortable="true" resizable="true" editable="true"></igc-column>
<igc-paginator></igc-paginator>
<igc-grid-toolbar>
<igc-grid-toolbar-title> Employees </igc-grid-toolbar-title>
<igc-grid-toolbar-actions>
<igc-grid-toolbar-hiding> </igc-grid-toolbar-hiding>
<igc-grid-toolbar-pinning> </igc-grid-toolbar-pinning>
<igc-grid-toolbar-exporter export-csv="true" export-excel="true"> </igc-grid-toolbar-exporter>
</igc-grid-toolbar-actions>
</igc-grid-toolbar>
</igc-tree-grid>
Puede ver el resultado del código de arriba al principio de este artículo en la sección Ejemplo de cuadrícula de árbol.
Primary and Foreign keys
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.
const 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 }
];
In the sample data above, all records have an ID, a ParentID and some additional properties like Name, JobTitle and Age. As mentioned previously, the ID of the records must be unique as it will be our primaryKey. The ParentID contains the ID of the parent node and could be set as a foreignKey. If a row has a ParentID that does not match any row in the tree grid, then that means this row is a root row.
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:
<igc-tree-grid auto-generate="false" name="treeGrid" id="treeGrid" primary-key="ID" foreign-key="ParentID" allow-filtering="true" moving="true" row-selection="multiple">
<igc-column field="Name" data-type="string"></igc-column>
<igc-column field="JobTitle" header="Job Title"></igc-column>
<igc-column field="Age" data-type="number"></igc-column>
</igc-tree-grid>
Además, habilitaremos la función de selección de filas de la cuadrícula de árbol mediante el uso de la propiedad rowSelection y también las funciones de filtrado, ordenación, edición, movimiento y cambio de tamaño para cada una de nuestras columnas.
<igc-tree-grid auto-generate="false" name="treeGrid" id="treeGrid" primary-key="ID" foreign-key="ParentID" allow-filtering="true" moving="true" row-selection="multiple">
<igc-column field="Name" data-type="string" sortable="true" editable="true" resizable="true"> </igc-column>
<igc-column field="JobTitle" header="Job Title" data-type="string" sortable="true" editable="true" resizable="true"> </igc-column>
<igc-column field="Age" data-type="number" sortable="true" editable="true" resizable="true"> </igc-column>
</igc-tree-grid>
Y aquí está el resultado final:
Persistence and Integration
La sangría de la celda de la cuadrícula de árbol persiste en otras entidades de cuadrícula de árbol, como el filtrado, la ordenación y la paginación.
- When
Sortingis applied on a column, the data rows get sorted by levels. This means that the root level rows will be sorted independently from their respective children. Their respective children collections will each be sorted independently as well and so on. - 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.
Web Components Tree Grid Styling Configuration
Además de los temas predefinidos, la cuadrícula se puede personalizar aún más configurando algunas de las propiedades CSS disponibles. En caso de que desee cambiar algunos de los colores, primero debe establecer una clase para la cuadrícula:
<igc-tree-grid class="tree-grid">
Luego configure las propiedades CSS relacionadas para esa clase:
.tree-grid {
--ig-grid-header-background: #494949;
--ig-grid-header-text-color: #FFF;
--ig-grid-expand-icon-color: #FFCD0F;
--ig-grid-expand-icon-hover-color: #E0B710;
--ig-grid-row-hover-background: #F8E495;
}
API References
Additional Resources
Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.