Edición por lotes y transacciones en cuadrículas de árboles Angular
La función de edición por lotes de IgxTreeGrid se basa en HierarchicalTransactionService
. Siga el tema Transaction Service class hierarchy
para ver una descripción general de igxHierarchicalTransactionService
y detalles sobre cómo se implementa.
A continuación se muestra un ejemplo detallado de cómo se habilita la edición por lotes para el componente Tree Grid.
Angular Ejemplo de Edición por Lotes y Transacciones de Tree Grid
El siguiente ejemplo muestra un escenario en el que treeGrid tiene habilitada batchEditing
y la edición de filas. Esto último garantizará que la transacción se agregue después de que se confirme la edición completa de la fila.
import { Component, OnInit, ViewChild } from '@angular/core' ;
import { IgxDialogComponent, IgxGridComponent, IgxTreeGridComponent, Transaction, IgxColumnComponent, IgxCellTemplateDirective, IgxButtonDirective } from 'igniteui-angular' ;
import { generateRandomInteger } from '../../data/utils' ;
import { generateEmployeeFlatData, IEmployee } from '../data/employees-flat' ;
import { IgxPreventDocumentScrollDirective } from '../../directives/prevent-scroll.directive' ;
@Component ({
selector : 'app-tree-grid-batch-editing-sample' ,
styleUrls : ['tree-grid-batch-editing-sample.component.scss' ],
templateUrl : 'tree-grid-batch-editing-sample.component.html' ,
imports : [IgxTreeGridComponent, IgxPreventDocumentScrollDirective, IgxColumnComponent, IgxCellTemplateDirective, IgxButtonDirective, IgxDialogComponent, IgxGridComponent]
})
export class TreeGridBatchEditingSampleComponent implements OnInit {
@ViewChild ('treeGrid' , { static : true }) public treeGrid: IgxTreeGridComponent;
@ViewChild (IgxDialogComponent, { static : true }) public dialog: IgxDialogComponent;
@ViewChild ('dialogGrid' , { read : IgxGridComponent, static : true }) public dialogGrid!: IgxGridComponent;
public data: IEmployee[];
public transactionsData: Transaction[] = [];
private nextRow = 1 ;
public ngOnInit(): void {
this .data = generateEmployeeFlatData();
}
public addRow ( ) {
const addedData: IEmployee = {
Age : 32 ,
HireDate : new Date (generateRandomInteger(2008 , 2015 ),
generateRandomInteger(0 , 12 ), generateRandomInteger(5 , 25 )),
ID : this .data.length + this .nextRow++,
Name: 'John Doe' ,
Phone : '(91) 745 6200' ,
OnPTO : false ,
ParentID : -1 ,
Title : 'Junior Sales Representative'
};
this .treeGrid.addRow(addedData);
}
public addChildRow (id ) {
const addedData: IEmployee = {
Age : generateRandomInteger(18 , 55 ),
HireDate : new Date (generateRandomInteger(2008 , 2015 ),
generateRandomInteger(0 , 12 ), generateRandomInteger(5 , 25 )),
ID : this .data.length + this .nextRow++,
Name: 'Added Addedington' ,
Phone : '(91) 745 6200' ,
OnPTO : false ,
ParentID : -1 ,
Title : 'Intern'
};
this .treeGrid.addRow(
addedData,
id);
}
public deleteRow (id ) {
this .treeGrid.deleteRow(id);
}
public undo ( ) {
this .treeGrid.endEdit(true );
this .treeGrid.transactions.undo();
}
public redo ( ) {
this .treeGrid.endEdit(true );
this .treeGrid.transactions.redo();
}
public commit ( ) {
this .treeGrid.transactions.commit(this .data);
this .dialog.close();
}
public cancel ( ) {
this .dialog.close();
}
public discard ( ) {
this .treeGrid.transactions.clear();
this .dialog.close();
}
public openCommitDialog ( ) {
this .dialog.open();
this .transactionsData = this .treeGrid.transactions.getAggregatedChanges(true );
this .dialogGrid.reflow();
}
public stateFormatter (value: string ) {
return value ? JSON .stringify(value) : '' ;
}
public typeFormatter (value: string ) {
return value ? value.toUpperCase() : '' ;
}
public classFromType(type : string ): string {
return type ? `transaction--${type .toLowerCase()} ` : '' ;
}
}
ts コピー <div class ="grid__wrapper" >
<igx-tree-grid [igxPreventDocumentScroll ]="true" #treeGrid [batchEditing ]="true" [data ]="data" primaryKey ="ID" foreignKey ="ParentID"
[width ]="'100%'" [height ]="'500px'" [rowEditable ]="true" >
<igx-column [filterable ]="false" width ="150" [editable ]="false" >
<ng-template igxCell let-cell ="cell" let-val >
<button igxButton (click )="deleteRow(cell.id.rowID)"
[disabled ]="cell.row.deleted" > Delete</button >
</ng-template >
</igx-column >
<igx-column [filterable ]="false" width ="180" [editable ]="false" >
<ng-template igxCell let-cell ="cell" let-val >
<button igxButton (click )="addChildRow(cell.id.rowID)" [disabled ]="cell.row.deleted" > Add Child
Row</button >
</ng-template >
</igx-column >
<igx-column field ="ID" header ="ID" dataType ="number" width ="200" > </igx-column >
<igx-column field ="Age" header ="Age" dataType ="number" width ="120" > </igx-column >
<igx-column field ="Name" header ="Full Name" dataType ="string" width ="240" > </igx-column >
<igx-column field ="Title" header ="Title" dataType ="string" width ="180" > </igx-column >
<igx-column field ="HireDate" header ="Hire Date" dataType ="date" width ="150" > </igx-column >
<igx-column field ="OnPTO" header ="On PTO" dataType ="boolean" width ="80" > </igx-column >
</igx-tree-grid >
<div class ="buttons-row" >
<button igxButton (click )="addRow()" > Add Root Level Row</button >
<div class ="buttons-wrapper" >
<button igxButton [disabled ]="!treeGrid.transactions.canUndo" (click )="undo()" > Undo</button >
<button igxButton [disabled ]="!treeGrid.transactions.canRedo" (click )="redo()" > Redo</button >
<button igxButton [disabled ]="treeGrid.transactions.getAggregatedChanges(false).length < 1"
(click )="openCommitDialog()" > Commit</button >
</div >
</div >
<igx-dialog title ="Submit the following transactions?" >
<igx-grid [igxPreventDocumentScroll ]="true" #dialogGrid [data ]="transactionsData" [rowHeight ]="64" [primaryKey ]="'id'"
width ="600px" height ="300px" [emptyGridMessage ]="'No available transactions'" >
<igx-column field ="id" header ="ID" [dataType ]="'string'" width ="100px" > </igx-column >
<igx-column field ="type" header ="Type" width ="150px" [sortable ]="true" >
<ng-template igxCell let-cell ="cell" let-val >
<span [class ]="classFromType(val)" > {{ typeFormatter(val) }}</span >
</ng-template >
</igx-column >
<igx-column field ="newValue" header ="Value" width ="900px" >
<ng-template igxCell let-cell ="cell" let-val >
<span class ="transaction-log" > {{ stateFormatter(val) }}</span >
</ng-template >
</igx-column >
</igx-grid >
<div class ="buttons-wrapper" >
<button igxButton (click )="commit()" > Commit</button >
<button igxButton (click )="discard()" > Discard</button >
<button igxButton (click )="cancel()" > Cancel</button >
</div >
</igx-dialog >
</div >
html コピー .grid__wrapper {
margin : 15px ;
}
h4 {
text-align : center;
padding-top : 2% ;
padding-bottom : 2% ;
}
.buttons-row {
display : flex;
flex-direction : row;
justify-content : space-between;
padding : 5px ;
}
.buttons-wrapper {
display : flex;
flex-direction : row;
justify-content : center;
padding : 10px 0 ;
}
.list-container {
width : 600px ;
height : 300px ;
overflow-y : visible;
}
.transaction--update , .transaction--delete , .transaction--add {
font-weight : 600 ;
}
.transaction--add {
color : #6b3 ;
}
.transaction--update {
color : #4a71b9 ;
}
.transaction--delete {
color : #ee4920 ;
}
.transaction-log {
word-wrap : none;
}
scss コピー
¿Te gusta esta muestra? Obtenga acceso a nuestro kit de herramientas de Ignite UI for Angular completo y comience a crear sus propias aplicaciones en minutos. Descárgalo gratis.
El estado de la transacción consta de todas las filas actualizadas, agregadas y eliminadas, y sus últimos estados.
Uso
Para comenzar, importe IgxTreeGridModule
en el archivo app.module.ts :
...
import { IgxTreeGridModule } from 'igniteui-angular' ;
@NgModule ({
...
imports : [..., IgxTreeGridModule],
...
})
export class AppModule {}
typescript
Luego, todo lo que necesitas hacer es habilitar batchEditing
desde tu Tree Grid:
<igx-tree-grid [data ]="data" [batchEditing ]="true" >
...
</igx-tree-grid >
html
Esto garantizará que se proporcione una instancia adecuada del servicio Transaction
para igx-tree-grid. El TransactionService
adecuado se proporciona a través de TransactionFactory
. Puede obtener más información sobre esta implementación interna en el tema de transacciones .
Después de habilitar la edición por lotes, defina un IgxTreeGrid
con una fuente de datos vinculada y rowEditable
configurado en verdadero y vincule:
<igx-tree-grid #treeGrid [batchEditing ]="true" [data ]="data" primaryKey ="employeeID" foreignKey ="PID"
width ="100%" height ="500px" rowEditable =true >
...
</igx-tree-grid >
...
<button igxButton (click )="addRow()" > Add Root Level Row</button >
<button igxButton [disabled ]="!treeGrid.transactions.canUndo" (click )="undo()" > Undo</button >
<button igxButton [disabled ]="!treeGrid.transactions.canRedo" (click )="redo()" > Redo</button >
<button igxButton [disabled ]="treeGrid.transactions.getAggregatedChanges(false).length < 1"
(click )="openCommitDialog()" > Commit</button >
...
html
El siguiente código demuestra el uso de la API HierarchicalTransactionService
: deshacer, rehacer y confirmar.
export class TreeGridBatchEditingSampleComponent {
@ViewChild ('treeGrid' , { read : IgxTreeGridComponent }) public treeGrid: IgxTreeGridComponent;
public undo ( ) {
this .treeGrid.endEdit(true );
this .treeGrid.transactions.undo();
}
public redo ( ) {
this .treeGrid.endEdit(true );
this .treeGrid.transactions.redo();
}
public commit ( ) {
this .treeGrid.transactions.commit(this .data);
this .dialog.close();
}
}
typescript
La API de transacciones no se encargará del final de la edición y deberá hacerlo usted mismo. De lo contrario, Tree Grid
permanecería en modo de edición. Una forma de hacerlo es llamando endEdit
en el método respectivo.
Eliminar un nodo principal en Tree Grid
tiene algunas peculiaridades. Si está utilizando datos jerárquicos, los hijos se eliminarán al eliminar a sus padres. Si está utilizando datos planos, puede establecer el comportamiento deseado utilizando la propiedad cascadeOnDelete
de Tree Grid
. Esta propiedad indica si los registros secundarios deben eliminarse cuando se eliminan los principales (de forma predeterminada, está establecido en true
).
Al deshabilitar la propiedad rowEditable
se modificará Tree Grid
para crear transacciones en el cambio de celda y no se expondrá la superposición de edición de filas en la interfaz de usuario.
Referencias de API
Recursos adicionales
Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.