Edición de celdas en cuadrícula de árbol React
La Ignite UI for React la edición de celdas en React Tree Grid, ofrece una gran capacidad de manipulación de datos del contenido de celdas individuales dentro del componente React Tree Grid y viene con una potente API para operaciones CRUD React. Es una característica fundamental en aplicaciones como hojas de cálculo, tablas de datos y cuadrículas de datos, que permite a los usuarios agregar, editar o actualizar datos dentro de celdas específicas. De forma predeterminada, la cuadrícula en Ignite UI for React se utiliza en la edición de celdas. Y debido a la plantilla de edición de celdas predeterminada, habrá diferentes editores según el tipo de datos de la columna Top of Form.
Además, puede definir sus propias plantillas personalizadas para acciones de actualización de datos y anular el comportamiento predeterminado para confirmar y descartar cualquier cambio.
React Tree Grid Cell Editing and Edit Templates Example
Edición de celdas
Editing through UI
Puede ingresar al modo de edición para una celda específica, cuando una celda editable está enfocada de una de las siguientes maneras:
- al hacer doble clic;
- con un solo clic: un solo clic ingresará al modo de edición solo si la celda seleccionada previamente estaba en modo de edición y la celda actualmente seleccionada es editable. Si la celda previamente seleccionada no estaba en modo de edición, un solo clic seleccionará la celda sin ingresar al modo de edición;
- al presionar una ENTER tecla;
- en la tecla presione F2;
Puede salir del modo de edición sin realizar los cambios de una de las siguientes maneras:
- en la tecla presione Escape;
- cuando realizas operaciones de ordenación, filtrado, búsqueda y ocultación;
Puede salir del modo de edición y confirmar los cambios de una de las siguientes maneras:
- al presionar una ENTER tecla;
- en la tecla presione F2;
- al presionar una TAB tecla;
- on single click to another cell - when you click on another cell in the
IgrTreeGrid, your changes will be submitted. - operaciones como paginación, cambio de tamaño, anclar o mover saldrán del modo de edición y se enviarán los cambios.
[!Note] The cell remains in edit mode when you scroll vertically or horizontally or click outside the
IgrTreeGrid. This is valid for both cell editing and row editing.
Editing through API
You can also modify the cell value through the IgrTreeGrid API but only if primary key is defined:
public updateCell() {
this.treeGrid.updateCell(newValue, rowID, 'Age');
}
Another way to update cell is directly through Update method of Cell:
public updateCell() {
const cell = this.treeGrid.getCellByColumn(rowIndex, 'Age');
// You can also get cell by rowID if primary key is defined
// const cell = this.treeGrid.getCellByKey(rowID, 'Age');
cell.update(9999);
}
Cell Editing Templates
Puede ver y obtener más información sobre las plantillas de edición de celdas predeterminadas en el tema de edición general.
Si desea proporcionar una plantilla personalizada que se aplicará a una celda, puede pasar dicha plantilla a la celda misma o a su encabezado. Primero cree la columna como lo haría normalmente:
<IgrColumn
field="race"
header="Race"
dataType="string"
editable={true}
inlineEditorTemplate={this.webGridCellEditCellTemplate}>
</IgrColumn>
y pase las plantillas a esta columna en el archivo index.ts:
public webGridCellEditCellTemplate = (e: IgrCellTemplateContext) => {
let cellValues: any = [];
let uniqueValues: any = [];
const cell = e.cell;
const colIndex = cell.id.columnID;
const field: string = this.grid1.getColumnByVisibleIndex(colIndex).field;
let index = 0;
for (const i of this.roleplayDataStats as any) {
if (uniqueValues.indexOf(i[field]) === -1) {
cellValues.push(
<>
<IgrSelectItem
selected={e.cell.value == i[field]}
value={i[field]}
>
<div>{i[field]}</div>
</IgrSelectItem>
</>
);
uniqueValues.push(i[field]);
}
index++;
}
return (
<>
<IgrSelect
onChange={(x: any) => {
setTimeout(() => {
cell.editValue = x.target.value;
});
}}
>
{cellValues}
</IgrSelect>
</>
);
};
Puede encontrar una muestra funcional de lo anterior aquí para mayor referencia:
CRUD operations
[!Note] Please keep in mind that when you perform some CRUD operation all of the applied pipes like filtering, sorting and grouping will be re-applied and your view will be automatically updated.
The IgrTreeGrid provides a straightforward API for basic CRUD operations.
Adding a new record
The IgrTreeGrid component exposes the addRow method which will add the provided data to the data source itself.
public addNewChildRow() {
// Adding a new record
// Assuming we have a `getNewRecord` method returning the new row data
// And specifying the parentRowID.
const record = this.getNewRecord();
this.treeGrid.addRow(record, 1);
}
Updating data in the Tree Grid
Updating data in the Tree Grid is achieved through updateRow and updateCell methods but only if the PrimaryKey for the grid is defined. You can also directly update a cell and/or a row value through their respective update methods.
// Updating the whole row
this.treeGrid.updateRow(newData, this.selectedCell.cellID.rowID);
// Just a particular cell through the Tree Grid API
this.treeGrid.updateCell(newData, this.selectedCell.cellID.rowID, this.selectedCell.column.field);
// Directly using the cell `update` method
this.selectedCell.update(newData);
// Directly using the row `update` method
const row = this.treeGrid.getRowByKey(rowID);
row.update(newData);
Deleting data from the Tree Grid
Please keep in mind that deleteRow method will remove the specified row only if a primaryKey is defined.
// Delete row through Tree Grid API
this.treeGrid.deleteRow(this.selectedCell.cellID.rowID);
// Delete row through row object
const row = this.treeGrid.getRowByIndex(rowIndex);
row.delete();
Cell Validation on Edit Event
Using the IgrTreeGrid's editing events, we can alter how the user interacts with the IgrTreeGrid.
In this example, we'll validate a cell based on the data entered in it by binding to the CellEdit event. If the new value of the cell does not meet our predefined criteria, we'll prevent it from reaching the data source by cancelling the event.
Lo primero que tenemos que hacer es enlazar al evento de la cuadrícula:
<IgrTreeGrid onCellEdit={handleCellEdit}>
</IgrTreeGrid>
The CellEdit emits whenever any cell's value is about to be committed. In our CellEdit definition, we need to make sure that we check for our specific column before taking any action:
public webTreeGridCellEdit(args: IgrGridEditEventArgs): void {
const column = args.detail.column;
if (column.field === 'Age') {
if (args.detail.newValue < 18) {
args.detail.cancel = true;
alert('Employees must be at least 18 years old!');
}
} else if (column.field === 'HireDate') {
if (args.detail.newValue > new Date().getTime()) {
args.detail.cancel = true;
alert('The employee hire date must be in the past!');
}
}
}
The result of the above validation being applied to our IgrTreeGrid can be seen in the below demo:
Styling
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:
<IgrTreeGrid className="treeGrid"></IgrTreeGrid>
Luego configure las propiedades CSS relacionadas para esa clase:
.treeGrid {
--ig-grid-edit-mode-color: orange;
--ig-grid-cell-editing-background: lightblue;
}