The Ignite UI for Web Components Cell Editing in Web Components Grid provides a great data manipulation capability of the content of individual cells within the Web Components Grid component and comes with powerful API for React CRUD operations. It is a fundamental feature in apps like spreadsheets, data tables, and data grids, allowing users to add, edit, or update data within specific cells.
By default, the Grid in Ignite UI for Web Components is used in cell editing. And due to the default cell editing template, there will be different editors based on the column data type Top of Form.
In addition, you can define your own custom templates for update-data actions and to override the default behavior for committing and discarding any changes.
Web Components Grid Cell Editing and Edit Templates Example
<!DOCTYPE html><html><head><title>Sample | Ignite UI | Web Components | infragistics</title><metacharset="UTF-8" /><linkrel="shortcut icon"href="https://static.infragistics.com/xplatform/images/browsers/wc.png" ><linkrel="stylesheet"href="https://fonts.googleapis.com/icon?family=Material+Icons" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Kanit&display=swap" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Titillium Web" /><linkrel="stylesheet"href="https://static.infragistics.com/xplatform/css/samples/shared.v8.css" /><linkrel="stylesheet"href="/src/index.css"type="text/css" /></head><body><divid="root"><divclass="container sample ig-typography"><divclass="container fill"><igc-gridauto-generate="false"id="grid"name="grid"id="grid"primary-key="ProductID"allow-filtering="true"><igc-paginatorper-page="10"></igc-paginator><igc-columnfield="ProductName"header="Product Name"data-type="string"sortable="true"has-summary="true"editable="true"resizable="true"></igc-column><igc-columnfield="UnitsInStock"header="Units in Stock"data-type="number"sortable="true"has-summary="true"editable="true"resizable="true"></igc-column><igc-columnfield="OrderDate"header="Order Date"data-type="date"sortable="true"has-summary="true"editable="true"resizable="true"></igc-column><igc-columnfield="Discontinued"header="Discontinued"data-type="boolean"sortable="true"has-summary="true"editable="true"></igc-column><igc-columnfield="ReorderLevel"header="Reorder Level"data-type="number"sortable="true"has-summary="true"editable="true"filterable="false"></igc-column></igc-grid></div></div></div><!-- This script is needed only for parcel and it will be excluded for webpack -->
<% if (false) { %><scriptsrc="src/index.ts"></script><% } %>
</body></html>html
Like this sample? Get access to our complete Ignite UI for Web Components toolkit and start building your own apps in minutes. Download it for free.
Cell Editing
Editing through UI
You can enter edit mode for specific cell, when an editable cell is focused in one of the following ways:
on double click;
on single click - Single click will enter edit mode only if the previously selected cell was in edit mode and currently selected cell is editable. If the previously selected cell was not in edit mode, single click will select the cell without entering edit mode;
on key press Enter;
on key press F2;
You can exit edit mode without committing the changes in one of the following ways:
on key press Escape;
when you perform sorting, filtering, searching and hiding operations;
You can exit edit mode and commit the changes in one of the following ways:
on key press Enter;
on key press F2;
on key press Tab;
on single click to another cell - when you click on another cell in the IgcGridComponent, your changes will be submitted.
operations like paging, resize, pin or move will exit edit mode and changes will be submitted.
The cell remains in edit mode when you scroll vertically or horizontally or click outside the IgcGridComponent. This is valid for both cell editing and row editing.
Editing through API
You can also modify the cell value through the IgcGridComponent API but only if primary key is defined:
Another way to update cell is directly through update method of Cell:
publicupdateCell() {
const cell = this.grid1.getCellByColumn(rowIndex, 'ReorderLevel');
// You can also get cell by rowID if primary key is defined// cell = this.grid1.getCellByKey(rowID, 'ReorderLevel');
cell.update(70);
}
typescript
Cell Editing Templates
You can see and learn more for default cell editing templates in the general editing topic.
If you want to provide a custom template which will be applied to a cell, you can pass such template either to the cell itself, or to its header. First create the column as you usually would:
import'igniteui-webcomponents-grids/grids/combined';
import { ComponentRenderer, WebGridDescriptionModule, WebSelectDescriptionModule } from'igniteui-webcomponents-core';
import { IgcGridComponent, IgcColumnComponent } from'igniteui-webcomponents-grids/grids';
import { RoleplayDataStatsItem, RoleplayDataStats } from'./RoleplayDataStats';
import { IgcCellTemplateContext } from'igniteui-webcomponents-grids/grids';
import { html, nothing } from'lit-html';
import"igniteui-webcomponents-grids/grids/themes/light/bootstrap.css";
import'igniteui-webcomponents/themes/light/bootstrap.css';
import { defineAllComponents } from'igniteui-webcomponents';
defineAllComponents();
import"./index.css";
exportclassSample{
private grid1: IgcGridComponent
private column1: IgcColumnComponent
private column2: IgcColumnComponent
private column3: IgcColumnComponent
private _bind: () =>void;
constructor() {
var grid1 = this.grid1 = document.getElementById('grid1') as IgcGridComponent;
var column1 = this.column1 = document.getElementById('column1') as IgcColumnComponent;
var column2 = this.column2 = document.getElementById('column2') as IgcColumnComponent;
var column3 = this.column3 = document.getElementById('column3') as IgcColumnComponent;
this._bind = () => {
grid1.data = this.roleplayDataStats;
column1.inlineEditorTemplate = this.webGridCellEditCellTemplate;
column2.inlineEditorTemplate = this.webGridCellEditCellTemplate;
column3.inlineEditorTemplate = this.webGridCellEditCellTemplate;
}
this._bind();
}
private _roleplayDataStats: RoleplayDataStats = null;
publicgetroleplayDataStats(): RoleplayDataStats {
if (this._roleplayDataStats == null)
{
this._roleplayDataStats = new RoleplayDataStats();
}
returnthis._roleplayDataStats;
}
private _componentRenderer: ComponentRenderer = null;
publicgetrenderer(): ComponentRenderer {
if (this._componentRenderer == null) {
this._componentRenderer = new ComponentRenderer();
var context = this._componentRenderer.context;
WebGridDescriptionModule.register(context);
WebSelectDescriptionModule.register(context);
}
returnthis._componentRenderer;
}
public webGridCellEditCellTemplate = (ctx: IgcCellTemplateContext) => {
let cellValues: any = [];
let uniqueValues: any = [];
let roleplayDataStats = this.grid1.data;
for(const i of (roleplayDataStats asany)){
const field: string = ctx.cell.column.field;
if(uniqueValues.indexOf(i[field]) === -1 )
{
if (ctx.cell.value == i[field]) {
cellValues.push(html`<igc-select-itemselectedvalue=${i[field]}>${(i[field])}</igc-select-item>`);
} else cellValues.push(html`<igc-select-itemvalue=${i[field]}>${(i[field])}</igc-select-item>`);
uniqueValues.push(i[field]);
}
}
return html`<igc-selectstyle="width:100%; height:100%; --ig-size: var(--ig-size-large);" @igcChange=${(e: any) => ctx.cell.editValue = e.detail.value}>${cellValues}</igc-select>
`;
}
}
new Sample();
ts
<!DOCTYPE html><html><head><title>Sample | Ignite UI | Web Components | infragistics</title><metacharset="UTF-8" /><linkrel="shortcut icon"href="https://static.infragistics.com/xplatform/images/browsers/wc.png" ><linkrel="stylesheet"href="https://fonts.googleapis.com/icon?family=Material+Icons" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Kanit&display=swap" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Titillium Web" /><linkrel="stylesheet"href="https://static.infragistics.com/xplatform/css/samples/shared.v8.css" /><linkrel="stylesheet"href="/src/index.css"type="text/css" /></head><body><divid="root"><divclass="container sample ig-typography"><divclass="container fill"><igc-gridauto-generate="false"name="grid1"id="grid1"primary-key="Name"><igc-columnfield="Name"header="Character Name"data-type="string"></igc-column><igc-columnfield="Race"header="Race"data-type="string"editable="true"name="column1"id="column1"></igc-column><igc-columnfield="Class"header="Class"editable="true"data-type="string"name="column2"id="column2"></igc-column><igc-columnfield="Age"header="Age"data-type="string"editable="true"></igc-column><igc-columnfield="Alignment"header="Alignment"editable="true"data-type="string"name="column3"id="column3"></igc-column></igc-grid></div></div></div><!-- This script is needed only for parcel and it will be excluded for webpack -->
<% if (false) { %><scriptsrc="src/index.ts"></script><% } %>
</body></html>html
/* shared styles are loaded from: *//* https://static.infragistics.com/xplatform/css/samples */css
Grid Excel Style Editing
Using Excel Style Editing allows the user to navigate trough the cells just as he would using the Excel, and ever so quickly edit them.
Implementing this custom functionality can be done by utilizing the events of the IgcGridComponent. First we hook up to the grid's keydown events, and from there we can implement two functionalities:
if (key == 13) {
let thisRow = activeElem.row;
const column = activeElem.column;
const rowInfo = grid.dataView;
// to find the next eligible cell, we will use a custom method that will check the next suitable indexlet nextRow = this.getNextEditableRowIndex(thisRow, rowInfo, event.shiftKey);
// and then we will navigate to it using the grid's built in method navigateTothis.grid.navigateTo(nextRow, column, (obj) => {
obj.target.activate();
this.grid.clearCellSelection();
this.cdr.detectChanges();
});
}
typescript
Key parts of finding the next eligible index would be:
//first we check if the currently selected cell is the first or the lastif (currentRowIndex < 0 || (currentRowIndex === 0 && previous) || (currentRowIndex >= dataView.length - 1 && !previous)) {
return currentRowIndex;
}
// in case using shift + enter combination, we look for the first suitable cell going up the fieldif (previous) {
return dataView.findLastIndex((rec, index) => index < currentRowIndex && this.isEditableDataRecordAtIndex(index, dataView));
}
// or for the next one down the fieldreturn dataView.findIndex((rec, index) => index > currentRowIndex && this.isEditableDataRecordAtIndex(index, dataView));
typescript
Please check the full sample for further reference:
<!DOCTYPE html><html><head><title>Sample | Ignite UI | Web Components | infragistics</title><metacharset="UTF-8" /><linkrel="shortcut icon"href="https://static.infragistics.com/xplatform/images/browsers/wc.png" ><linkrel="stylesheet"href="https://fonts.googleapis.com/icon?family=Material+Icons" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Kanit&display=swap" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Titillium Web" /><linkrel="stylesheet"href="https://static.infragistics.com/xplatform/css/samples/shared.v8.css" /><linkrel="stylesheet"href="/src/index.css"type="text/css" /></head><body><divid="root"><divclass="container sample ig-typography"><divclass="container fill"><igc-gridauto-generate="false"primary-key="ProductID"cell-selection="single"name="grid1"id="grid1"><igc-columnfield="ProductID"header="Product ID"editable="true"groupable="true"hidden="true"></igc-column><igc-columnfield="ProductName"header="Product Name"data-type="string"editable="true"></igc-column><igc-columnfield="UnitPrice"header="Unit Price"data-type="number"editable="true"></igc-column><igc-columnfield="QuantityPerUnit"header="Quantity Per Unit"groupable="true"data-type="string"editable="true"></igc-column><igc-columnfield="ReorderLevel"header="Reorder Level"data-type="number"groupable="true"editable="true"></igc-column></igc-grid></div></div></div><!-- This script is needed only for parcel and it will be excluded for webpack -->
<% if (false) { %><scriptsrc="src/index.ts"></script><% } %>
</body></html>html
/* shared styles are loaded from: *//* https://static.infragistics.com/xplatform/css/samples */css
Main benefits of the above approach include:
Constant edit mode: typing while a cell is selected will immediately enter edit mode with the value typed, replacing the existing one
Any non-data rows are skipped when navigating with Enter/Shift+Enter. This allows users to quickly cycle through their values.
CRUD operations
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 IgcGridComponent provides a straightforward API for basic CRUD operations.
Adding a new record
The IgcGridComponent component exposes the addRow method which will add the provided data to the data source itself.
// Adding a new record// Assuming we have a `getNewRecord` method returning the new row data.const record = this.getNewRecord();
this.grid.addRow(record);
typescript
Updating data in the Grid
Updating data in the 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 rowthis.grid.updateRow(newData, this.selectedCell.cellID.rowID);
// Just a particular cell through the Grid APIthis.grid.updateCell(newData, this.selectedCell.cellID.rowID, this.selectedCell.column.field);
// Directly using the cell `update` methodthis.selectedCell.update(newData);
// Directly using the row `update` methodconst row = this.grid.getRowByKey(rowID);
row.update(newData);
typescript
Deleting data from the Grid
Please keep in mind that deleteRow method will remove the specified row only if a primaryKey is defined.
// Delete row through Grid APIthis.grid.deleteRow(this.selectedCell.cellID.rowID);
// Delete row through row objectconst row = this.grid.getRowByIndex(rowIndex);
row.delete();
typescript
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.
The first thing we need to do is bind to the grid's event:
constructor() {
var grid = document.getElementById('grid') as IgcGridComponent;
this.webGridCellEdit = this.webGridCellEdit.bind(this);
grid.addEventListener("cellEdit", this.webGridCellEdit);
}
typescript
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 webGridCellEdit(event: CustomEvent<IgcGridEditEventArgs>): void {
const column = event.detail.column;
if (column.field === 'UnitsOnOrder') {
const rowData = event.detail.rowData;
if (!rowData) {
return;
}
if (event.detail.newValue > rowData.UnitsInStock) {
event.cancel = true;
alert("You cannot order more than the units in stock!");
}
}
}
typescript
If the value entered in a cell under the Units On Order column is larger than the available amount (the value under Units in Stock), the editing will be cancelled and the user will be alerted to the cancellation.
The result of the above validation being applied to our IgcGridComponent can be seen in the below demo:
EXAMPLE
TS
HTML
CSS
import'igniteui-webcomponents-grids/grids/combined';
import { ComponentRenderer, WebGridDescriptionModule } from'igniteui-webcomponents-core';
import { IgcGridComponent, IgcColumnComponent } from'igniteui-webcomponents-grids/grids';
import NwindData from'./NwindData.json';
import { IgcGridEditEventArgs } from'igniteui-webcomponents-grids/grids';
import"igniteui-webcomponents-grids/grids/themes/light/bootstrap.css";
import"./index.css";
exportclassSample{
private grid1: IgcGridComponent
private unitsInStock: IgcColumnComponent
private unitsOnOrder: IgcColumnComponent
private _bind: () =>void;
constructor() {
var grid1 = this.grid1 = document.getElementById('grid1') as IgcGridComponent;
this.webGridEditingEventsCellEdit = this.webGridEditingEventsCellEdit.bind(this);
var unitsInStock = this.unitsInStock = document.getElementById('UnitsInStock') as IgcColumnComponent;
var unitsOnOrder = this.unitsOnOrder = document.getElementById('UnitsOnOrder') as IgcColumnComponent;
this._bind = () => {
grid1.data = this.nwindData;
grid1.addEventListener("cellEdit", this.webGridEditingEventsCellEdit);
}
this._bind();
}
private _nwindData: any[] = NwindData;
publicgetnwindData(): any[] {
returnthis._nwindData;
}
private _componentRenderer: ComponentRenderer = null;
publicgetrenderer(): ComponentRenderer {
if (this._componentRenderer == null) {
this._componentRenderer = new ComponentRenderer();
var context = this._componentRenderer.context;
WebGridDescriptionModule.register(context);
}
returnthis._componentRenderer;
}
public webGridEditingEventsCellEdit(args: CustomEvent<IgcGridEditEventArgs>): void {
var d = args.detail;
if (d.column != null && d.column.field == "UnitsOnOrder") {
if (d.newValue > d.rowData.UnitsInStock) {
d.cancel = true;
alert("You cannot order more than the units in stock!")
}
}
}
}
new Sample();
ts
<!DOCTYPE html><html><head><title>Sample | Ignite UI | Web Components | infragistics</title><metacharset="UTF-8" /><linkrel="shortcut icon"href="https://static.infragistics.com/xplatform/images/browsers/wc.png" ><linkrel="stylesheet"href="https://fonts.googleapis.com/icon?family=Material+Icons" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Kanit&display=swap" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Titillium Web" /><linkrel="stylesheet"href="https://static.infragistics.com/xplatform/css/samples/shared.v8.css" /><linkrel="stylesheet"href="/src/index.css"type="text/css" /></head><body><divid="root"><divclass="container sample ig-typography"><divclass="container fill"><igc-gridauto-generate="false"primary-key="ProductID"name="grid1"id="grid1"><igc-columnfield="ProductName"header="Product Name"data-type="string"></igc-column><igc-columnfield="UnitPrice"header="Unit Price"data-type="number"editable="true"></igc-column><igc-columnname="UnitsInStock"id="UnitsInStock"field="UnitsInStock"header="Units In Stock"data-type="number"editable="true"></igc-column><igc-columnname="UnitsOnOrder"id="UnitsOnOrder"field="UnitsOnOrder"header="Units on Order"data-type="number"editable="true"></igc-column></igc-grid></div></div></div><!-- This script is needed only for parcel and it will be excluded for webpack -->
<% if (false) { %><scriptsrc="src/index.ts"></script><% } %>
</body></html>html
/* shared styles are loaded from: *//* https://static.infragistics.com/xplatform/css/samples */css
Styling
In addition to the predefined themes, the grid could be further customized by setting some of the available CSS properties.
In case you would like to change some of the colors, you need to set a class for the grid first:
<igc-gridclass="grid"></igc-grid>html
Then set the related CSS properties for that class:
<!DOCTYPE html><html><head><title>Sample | Ignite UI | Web Components | infragistics</title><metacharset="UTF-8" /><linkrel="shortcut icon"href="https://static.infragistics.com/xplatform/images/browsers/wc.png" ><linkrel="stylesheet"href="https://fonts.googleapis.com/icon?family=Material+Icons" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Kanit&display=swap" /><linkrel="stylesheet"href="https://fonts.googleapis.com/css?family=Titillium Web" /><linkrel="stylesheet"href="https://static.infragistics.com/xplatform/css/samples/shared.v8.css" /><linkrel="stylesheet"href="/src/index.css"type="text/css" /></head><body><divid="root"><divclass="container sample ig-typography"><divclass="container fill"><igc-gridauto-generate="false"id="grid"name="grid"id="grid"primary-key="ProductID"allow-filtering="true"><igc-paginatorper-page="10"></igc-paginator><igc-columnfield="ProductName"header="Product Name"data-type="string"sortable="true"has-summary="true"editable="true"resizable="true"></igc-column><igc-columnfield="UnitsInStock"header="Units in Stock"data-type="number"sortable="true"has-summary="true"editable="true"resizable="true"></igc-column><igc-columnfield="OrderDate"header="Order Date"data-type="date"sortable="true"has-summary="true"editable="true"resizable="true"></igc-column><igc-columnfield="Discontinued"header="Discontinued"data-type="boolean"sortable="true"has-summary="true"editable="true"></igc-column><igc-columnfield="ReorderLevel"header="Reorder Level"data-type="number"sortable="true"has-summary="true"editable="true"filterable="false"></igc-column></igc-grid></div></div></div><!-- This script is needed only for parcel and it will be excluded for webpack -->
<% if (false) { %><scriptsrc="src/index.ts"></script><% } %>
</body></html>html