Web Components Grid의 Ignite UI for Web Components Cell Editing은 Web Components Grid 구성 요소 내의 개별 셀의 내용에 대한 뛰어난 데이터 조작 기능을 제공하며 React CRUD 작업을 위한 강력한 API와 함께 제공됩니다. 스프레드시트, 데이터 테이블 및 데이터 그리드와 같은 앱에서 기본적인 기능으로, 사용자가 특정 셀 내에서 데이터를 추가, 편집 또는 업데이트할 수 있습니다. 기본적으로 Ignite UI for Web Components의 Grid는 셀 편집에 사용됩니다. 그리고 기본 셀 편집 템플릿으로 인해 Top of Form의 열 데이터 유형에 따라 다른 편집기가 있습니다.
또한 데이터 업데이트 작업에 대한 사용자 정의 템플릿을 정의하고 변경 사항 커밋 및 삭제에 대한 기본 동작을 재정의할 수 있습니다.
<!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
셀을 업데이트하는 또 다른 방법은 다음과 같은 방법을 사용하는 update 것입니다. 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
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
그리드 엑셀 스타일 편집
Excel 스타일 편집을 사용하면 사용자는 Excel을 사용하는 것처럼 셀을 탐색하고 신속하게 편집할 수 있습니다.
이 사용자 정의 기능을 구현하려면 IgcGridComponent의 이벤트를 활용하면 됩니다. 먼저 그리드의 keydown 이벤트에 연결하고 거기에서 두 가지 기능을 구현할 수 있습니다.
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
다음 적격 지수를 찾는 주요 부분은 다음과 같습니다.
//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
자세한 내용은 전체 샘플을 확인하세요.
Web Components 그리드 Excel 스타일 편집 샘플
EXAMPLE
위 접근 방식의 주요 이점은 다음과 같습니다.
지속적인 편집 모드: 셀이 선택된 동안 입력하면 입력된 값으로 즉시 편집 모드로 들어가 기존 값을 대체합니다.
Enter / Shift+Enter 를 사용하여 탐색할 때 데이터가 아닌 행은 건너뜁니다. 이를 통해 사용자는 해당 값을 빠르게 순환할 수 있습니다.
CRUD 작업
일부 CRUD 작업을 수행하면 필터링, 정렬, 그룹화 등 적용된 모든 파이프가 다시 적용되고 뷰가 자동으로 업데이트된다는 점을 명심하세요.
// Adding a new record// Assuming we have a `getNewRecord` method returning the new row data.const record = this.getNewRecord();
this.grid.addRow(record);
typescript
그리드에서 데이터 업데이트
그리드의 데이터 업데이트는 updateRow 및 updateCell 메소드를 통해 이루어지지만 그리드의 PrimaryKey가 정의된 경우에만 가능합니다. 또한 해당 업데이트 방법을 통해 셀 및/또는 행 값을 직접 업데이트할 수도 있습니다.
// 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
이 예에서는 CellEdit 이벤트에 바인딩하여 입력된 데이터를 기반으로 셀의 유효성을 검사합니다. 셀의 새 값이 사전 정의된 기준을 충족하지 않는 경우 이벤트를 취소하여 데이터 소스에 도달하지 못하게 합니다.
가장 먼저 해야 할 일은 그리드의 이벤트에 바인딩하는 것입니다.
constructor() {
var grid = document.getElementById('grid') as IgcGridComponent;
this.webGridCellEdit = this.webGridCellEdit.bind(this);
grid.addEventListener("cellEdit", this.webGridCellEdit);
}
typescript
CellEdit 셀의 값이 커밋되려고 할 때마다 내보냅니다. CellEdit 정의에서 조치를 취하기 전에 특정 열을 확인해야 합니다.
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
주문 단위 열 아래의 셀에 입력된 값이 사용 가능한 금액(재고 단위 아래의 값)보다 큰 경우 편집이 취소되고 사용자에게 취소 알림이 표시됩니다.
import'igniteui-webcomponents-grids/grids/combined';
import { ComponentRenderer, WebGridDescriptionModule } from'igniteui-webcomponents-core';
import { IgcGridComponent } 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 _bind: () =>void;
constructor() {
var grid1 = this.grid1 = document.getElementById('grid1') as IgcGridComponent;
this.webGridEditingEventsCellEdit = this.webGridEditingEventsCellEdit.bind(this);
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-columnfield="UnitsInStock"header="Units In Stock"data-type="number"editable="true"></igc-column><igc-columnfield="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
스타일링
사전 정의된 테마 외에도 사용 가능한 CSS 속성 중 일부를 설정하여 그리드를 추가로 사용자 정의할 수 있습니다. 일부 색상을 변경하려면 먼저 그리드에 대한 클래스를 설정해야 합니다.
<!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