Angular 그리드 셀 편집
Ignite UI for Angular 뛰어난 데이터 조작 기능과 Angular CRUD 작업을 위한 강력한 API를 제공합니다. 기본적으로 Grid는 셀 편집에 사용되며 기본 셀 편집 템플릿 덕분에 열 데이터 유형에 따라 다른 편집기가 표시됩니다. 또한 update-data 작업에 대한 사용자 정의 템플릿을 정의하고 변경 사항을 커밋하고 삭제하기 위한 기본 동작을 재정의할 수 있습니다.
Angular Grid cell editing and edit templates Example
Note
By using igxCellEditor with any type of editor component, the keyboard navigation flow will be disrupted. The same applies to direct editing of the custom cell that enters edit mode. This is because the focus will remain on the cell element, not on the editor component that we've added - igxSelect, igxCombo, etc. This is why we should take leverage of the igxFocus directive, which will move the focus directly in the in-cell component and will preserve a fluent editing flow of the cell/row.
셀 편집
Editing through UI
다음 방법 중 하나로 편집 가능한 셀에 초점이 맞춰지면 특정 셀에 대한 편집 모드로 들어갈 수 있습니다.
- 두 번 클릭하면;
- 한 번 클릭 시 - 이전에 선택한 셀이 편집 모드이고 현재 선택한 셀이 편집 가능한 경우에만 한 번 클릭하면 편집 모드로 들어갑니다. 이전에 선택한 셀이 편집 모드가 아닌 경우 한 번 클릭하면 편집 모드로 들어가지 않고 셀이 선택됩니다.
- on key press
Enter; - on key press
F2;
다음 방법 중 하나로 변경 사항을 커밋하지 않고 편집 모드를 종료할 수 있습니다.
- on key press
Escape; - 정렬, 필터링, 검색 및 숨기기 작업을 수행할 때
다음 방법 중 하나로 편집 모드를 종료하고 변경 사항을 커밋 할 수 있습니다.
- on key press
Enter; - on key press
F2; - on key press
Tab; - 다른 셀을 한 번 클릭하면 - 그리드의 다른 셀을 클릭하면 변경 사항이 제출됩니다.
- 페이징, 크기 조정, 고정 또는 이동과 같은 작업을 수행하면 편집 모드가 종료되고 변경 사항이 제출됩니다.
Note
세로 또는 가로로 스크롤하거나 그리드 외부를 클릭하면 셀은 편집 모드로 유지됩니다. 이는 셀 편집과 행 편집 모두에 유효합니다.
Editing through API
IgxGrid API를 통해 셀 값을 수정할 수도 있지만 기본 키가 정의된 경우에만 가능합니다.
public updateCell() {
this.grid1.updateCell(newValue, rowID, 'ReorderLevel');
}
Another way to update cell is directly through update method of IgxGridCell:
public updateCell() {
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);
}
Cell Editing Templates
일반 편집 항목에서 기본 셀 편집 템플릿에 대해 자세히 알아보고 확인할 수 있습니다.
If you want to provide a custom template which will be applied when a cell is in edit mode, you can make use of the igxCellEditor directive. To do this, you need to pass an ng-template marked with the igxCellEditor directive and properly bind your custom control to the cell.editValue:
<igx-column field="class" header="Class" [editable]="true">
<ng-template igxCellEditor let-cell="cell" let-value>
<igx-select class="cell-select" [(ngModel)]="cell.editValue" [igxFocus]="true">
<igx-select-item *ngFor="let class of classes" [value]="class">
{{ class }}
</igx-select-item>
</igx-select>
</ng-template>
</igx-column>
This code is used in the sample below which implements an IgxSelectComponent in the cells of the Race, Class and Alignment columns.
Note
Any changes made to the cell's editValue in edit mode, will trigger the appropriate editing event on exit and apply to the transaction state (if transactions are enabled).
Note
The cell template igxCell controls how a column's cells are shown when outside of edit mode.
The cell editing template directive igxCellEditor, handles how a column's cells in edit mode are displayed and controls the edited cell's edit value.
Note
By using igxCellEditor with any type of editor component, the keyboard navigation flow will be disrupted. The same applies to direct editing of the custom cell that enters edit mode. This is because the focus will remain on the cell element, not on the editor component that we've added - igxSelect, igxCombo, etc. This is why we should take leverage of the igxFocus directive, which will move the focus directly in the in-cell component and will preserve a fluent editing flow of the cell/row.
열과 해당 템플릿을 구성하는 방법에 대한 자세한 내용은 그리드 열 구성 설명서를 참조하세요.
Grid Excel Style Editing
Excel 스타일 편집을 사용하면 사용자는 Excel을 사용하는 것처럼 셀을 탐색하고 신속하게 편집할 수 있습니다.
이 사용자 정의 기능을 구현하려면 그리드의 이벤트를 활용하면 됩니다. 먼저 그리드의 keydown 이벤트에 연결하고 거기에서 두 가지 기능을 구현할 수 있습니다.
- 상수 편집 모드
public keydownHandler(event) {
const key = event.keyCode;
const grid = this.grid;
const activeElem = grid.navigation.activeNode;
if(
(key >= 48 && key <= 57) ||
(key >= 65 && key <= 90) ||
(key >= 97 && key <= 122)){
// Number or Alphabet upper case or Alphabet lower case
const columnName = grid.getColumnByVisibleIndex(activeElem.column).field;
const cell = grid.getCellByColumn(activeElem.row, columnName);
if (cell && !cell.editMode) {
cell.editMode = true;
cell.editValue = event.key;
this.shouldAppendValue = true;
} else if (cell && cell.editMode && this.shouldAppendValue) {
event.preventDefault();
cell.editValue = cell.editValue + event.key;
this.shouldAppendValue = false;
}
}
}
Enter/Shift+Enternavigation
if (key == 13) {
let thisRow = activeElem.row;
const column = activeElem.column;
const rowInfo = grid.dataView;
// to find the next eiligible cell, we will use a custom method that will check the next suitable index
let nextRow = this.getNextEditableRowIndex(thisRow, rowInfo, event.shiftKey);
// and then we will navigate to it using the grid's built in method navigateTo
this.grid.navigateTo(nextRow, column, (obj) => {
obj.target.activate();
this.grid.clearCellSelection();
this.cdr.detectChanges();
});
}
다음 적격 지수를 찾는 주요 부분은 다음과 같습니다.
//first we check if the currently selected cell is the first or the last
if (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 field
if(previous){
return dataView.findLastIndex((rec, index) => index < currentRowIndex && this.isEditableDataRecordAtIndex(index, dataView));
}
// or for the next one down the field
return dataView.findIndex((rec, index) => index > currentRowIndex && this.isEditableDataRecordAtIndex(index, dataView));
자세한 내용은 전체 샘플을 확인하세요.
Angular Grid Excel Style Editing Sample
위 접근 방식의 주요 이점은 다음과 같습니다.
- 지속적인 편집 모드: 셀이 선택된 동안 입력하면 입력된 값으로 즉시 편집 모드로 들어가 기존 값을 대체합니다.
- Any non-data rows are skipped when navigating with
Enter/Shift+Enter. This allows users to quickly cycle through their values.
CRUD operations
Note
일부 CRUD 작업을 수행하면 필터링, 정렬 및 그룹화와 같은 적용된 모든 파이프가 다시 적용되고 보기가 자동으로 업데이트된다는 점을 명심하세요.
The IgxGridComponent provides a straightforward API for basic CRUD operations.
Adding a new record
The Grid 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);
Updating data in the Grid
Updating data in the Grid is achieved through updateRow and updateCell methods but only if primary key 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.grid.updateRow(newData, this.selectedCell.cellID.rowID);
// Just a particular cell through the Grid API
this.grid.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.grid.getRowByKey(rowID);
row.update(newData);
Deleting data from the Grid
Please keep in mind that deleteRow() method will remove the specified row only if primary key is defined.
// Delete row through Grid API
this.grid.deleteRow(this.selectedCell.cellID.rowID);
// Delete row through row object
const row = this.grid.getRowByIndex(rowIndex);
row.delete();
이는 반드시 igx-grid와 관련될 필요는 없지만 사용자 상호 작용에 연결될 수 있습니다. 예를 들어 버튼 클릭은 다음과 같습니다.
<button igxButton igxRipple (click)="deleteRow($event)">Delete Row</button>
Cell validation on edit event
Using the grid's editing events we can alter how the user interacts with the grid.
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 (event.cancel = true). We'll also display a custom error message using IgxToast.
가장 먼저 해야 할 일은 그리드의 이벤트에 바인딩하는 것입니다.
<igx-grid (cellEdit)="handleCellEdit($event)"
...>
...
</igx-grid>
The cellEdit emits whenever any cell's value is about to be committed. In our handleCellEdit definition, we need to make sure that we check for our specific column before taking any action:
export class MyGridEventsComponent {
public handleCellEdit(event: IGridEditEventArgs): void {
const column = event.column;
if (column.field === 'Ordered') {
const rowData = event.rowData;
if (!rowData) {
return;
}
if (event.newValue > rowData.UnitsInStock) {
event.cancel = true;
this.toast.open();
}
}
}
}
주문 열 아래 셀에 입력한 값이 사용 가능한 금액(재고 단위 아래 값)보다 큰 경우 편집이 취소되고 오류 메시지와 함께 토스트가 표시됩니다.
The result of the above validation being applied to our igx-grid can be seen in the below demo:
스타일링
The IgxGrid allows for its cells to be styled through the Ignite UI for Angular Theme Library. The grid's grid-theme exposes a wide range of properties, which allow users to style many different aspects of the grid.
아래 단계에서는 편집 모드에서 그리드 셀의 스타일을 지정하는 방법과 해당 스타일의 범위를 지정하는 방법을 살펴보겠습니다.
In order to use the Ignite UI Theming Library, we must first import the theme index file in our global styles:
Importing style library
@use "igniteui-angular/theming" as *;
// IMPORTANT: Prior to Ignite UI for Angular version 13 use:
// @import '~igniteui-angular/lib/core/styles/themes/index';
이제 Ignite UI for Angular에서 제공하는 모든 기능을 활용할 수 있습니다.
Defining a palette
After we've properly imported the index file, we create a custom palette that we can use. Let's define three colors that we like and use them to build a palette with palette:
$white: #fff;
$blue: #4567bb;
$gray: #efefef;
$color-palette: palette(
$primary: $white,
$secondary: $blue,
$surface: $gray
);
Defining themes
We can now define the theme using our palette. The cells are styled by the grid-theme, so we can use that to generate a theme for our IgxGrid:
$custom-grid-theme: grid-theme(
$cell-editing-background: $blue,
$cell-edited-value-color: $white,
$cell-active-border-color: $white,
$edit-mode-color: color($color-palette, "secondary", 200)
);
Applying the theme
The easiest way to apply our theme is with a sass @include statement in the global styles file:
@include grid($custom-grid-theme);
Demo
In addition to the steps above, we can also style the controls that are used for the cells' editing templates: input-group, datepicker & checkbox
Note
The sample will not be affected by the selected global theme from Change Theme.
API References
- IgxGridCell
- IgxGridComponent 스타일s_IgxGridRow
- IgxInput 지시어
- IgxDatePicker구성 요소
- IgxDatePicker구성 요소 스타일
- IgxCheckbox구성요소
- IgxCheckbox구성 요소 스타일
- Igx오버레이
- Igx오버레이 스타일