Web Components Grid セル編集

    Web Components Grid の Ignite UI for Web Components セル編集機能は、Web Components Grid コンポーネント内の個々のセルのコンテンツの優れたデータ操作機能を提供し、React CRUD 操作用の強力な API を備えています。これはスプレッドシート、データ テーブル、データ グリッドなどのアプリの基本的な機能であり、ユーザーが特定のセル内のデータを追加、編集、更新できるようにします。 デフォルトでは、Ignite UI for Web Components の Grid がセル編集に使用されます。また、デフォルトのセル編集テンプレートにより、列のデータ型 「Top of Form」 に基づいて異なるエディターが存在します。

    さらに、データ更新アクション用の独自のカスタム テンプレートを定義したり、変更をコミット/破棄したりするためのデフォルトの動作をオーバーライドすることもできます。

    Web Components Grid セル編集と編集テンプレートの例

    セルの編集

    UI を介した編集

    編集可能なセルがフォーカスされたときに以下のいずれかの方法で特定のセルを編集モードにすることができます。

    • ダブル クリック
    • シングル クリック - 以前選択したセルが編集モードで現在選択したセルが編集可能な場合のみ、シングル クリックで編集モードに入ります。以前選択したセルが編集モードではない場合、編集モードに入らずにシングル クリックでセルを選択します。
    • Enter キーの押下
    • F2 キーの押下

    変更をコミットしない場合も以下の方法で編集モードを終了できます。

    • Escape キーの押下;
    • ソート、フィルターリング、検索、非表示操作の実行時。

    変更をコミットしない場合も以下の方法で編集モードを終了できます。

    • Enter キーの押下
    • F2 キーの押下
    • Tab キーの押下
    • 他のセルをシングル クリック - IgcGridComponent で他のセルをクリックしたときに変更がサブミットされます。
    • その他の操作 (ページング、サイズ変更、ピン固定、移動など) は、編集モードを終了して変更を送信します。

    [!Note] セルは、垂直/水平方向へのスクロールや IgcGridComponent 以外をクリックした場合も編集モードのままです。セル編集と行編集両方で有効です。

    API を介した編集

    プライマリキーが定義されている場合のみ IgcGridComponent API でもセル値を変更することができます。

    public updateCell() {
        this.grid1.updateCell(newValue, rowID, 'ReorderLevel');
    }
    

    セルを更新するその他の方法として IgcCellupdate メソッドで直接更新する方法があります。

    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);
    }
    

    セル編集テンプレート

    デフォルトのセル編集テンプレートの詳細については、編集トピックを参照してください。

    セルに適用されるカスタム テンプレートを提供する場合は、そのテンプレートをセル自体またはそのヘッダーに渡すことができます。まず、通常どおりに列を作成します。

    <igc-column
        field="Race"
        data-type="string"
        editable="true"
        id="column1">
    </igc-column>
    

    そして、テンプレートを index.ts ファイルのこの列に渡します。

    constructor() {
        var grid1 = document.getElementById('grid1') as IgcGridComponent;
        var column1 = document.getElementById('column1') as IgcColumnComponent;
        var column2 = document.getElementById('column2') as IgcColumnComponent;
        var column3 = document.getElementById('column3') as IgcColumnComponent;
    
        grid1.data = this.webGridCellEditSampleRoleplay;
        column1.inlineEditorTemplate = this.webGridCellEditCellTemplate;
        column2.inlineEditorTemplate = this.webGridCellEditCellTemplate;
        column3.inlineEditorTemplate = this.webGridCellEditCellTemplate;
    }
    
    
    public webGridCellEditCellTemplate = (ctx: IgcCellTemplateContext) => {
        let cellValues: any = [];
        let uniqueValues: any = [];
        for(const i of (this.webGridCellEditSampleRoleplay as any)){
            const field: string = ctx.cell.column.field;
            if(uniqueValues.indexOf(i[field]) === -1 )
            {
                cellValues.push(html`<igc-select-item value=${i[field]}>${(i[field])}</igc-select-item>`);
                uniqueValues.push(i[field]);
            }
        }
        return html`
            <igc-select style="width:100%; height:100%" size="large" @igcChange=${(e: any) => ctx.cell.editValue = e.detail.value}>
                ${cellValues}
            </igc-select>
        `;
    }
    

    上記のサンプルは、こちらで参照できます。

    Grid Excel スタイル編集

    Excel スタイル編集を使用すると、Excel を使用する場合と同じようにセルをナビゲートし、すばやく編集できます。

    このカスタム機能を実装するには、IgcGridComponent のイベントを使用します。最初にグリッドの keydown イベントにフックし、そこから 2 つの機能を実装できます。

    • 常時編集モード
    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 && !grid.crudService.cellInEditMode) {
                grid.crudService.enterEditMode(cell);
                cell.editValue = event.key;
            }
        }
    }
    
    • Enter/Shift+Enter ナビゲーション
    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 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));
    

    詳細については、サンプルを参照してください。

    Web Components Grid Excel スタイル編集のサンプル

    上記のアプローチの主な利点は次のとおりです:

    • 常時編集モード: セルが選択されているときに入力すると、編集モードに入り、入力された値が既存の値を置き換えます。
    • Enter/Shift+Enter で移動する場合、データ以外の行はスキップされます。これにより、ユーザーは値をすばやく切り替えることができます。

    CRUD 操作

    [!Note] CRUD 操作を実行した場合、filteringsortinggrouping などのパイプが再適用されるため、ビューが自動的に更新されることに注意してください。

    IgcGridComponent は基本的な CRUD 操作のための簡易な API を提供します。

    新しいレコードの追加

    IgcGridComponent コンポーネントは、提供したデータをデータ ソースに追加する addRow メソッドを公開します。

    // Adding a new record
    // Assuming we have a `getNewRecord` method returning the new row data.
    const record = this.getNewRecord();
    this.grid.addRow(record);
    

    データを Grid で更新

    Grid のデータ更新は、グリッドで PrimaryKey が定義されている場合のみ updateRowupdateCell メソッドで行うことができます。セルと行の値またはそのいずれかを各 update メソッドで直接更新できます。

    // 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);
    

    Grid からデータを削除

    deleteRow メソッドは、primaryKey が定義されている場合に指定した行のみを削除することに注意してください。

    // 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();
    

    編集イベントでのセル検証

    IgcGridComponent の編集イベントを使用して、ユーザーが IgcGridComponent を操作する方法を変更できます。

    この例では、CellEdit イベントにバインドすることにより、入力されたデータに基づいてセルを検証します。セルの新しい値が事前定義された基準を満たしていない場合、イベントをキャンセルすることでデータソースに到達しないようにします。

    最初に必要なことは、グリッドのイベントにバインドすることです。

    constructor() {
        var grid = document.getElementById('grid') as IgcGridComponent;
        this.webGridCellEdit = this.webGridCellEdit.bind(this);
        grid.addEventListener("cellEdit", this.webGridCellEdit);
    }
    

    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!");
                }
        }
    }
    
    

    Units On Order (注文済み) 列の下のセルに入力された値が使用可能量 (Units in Stock、在庫数 の値) よりも大きい場合、編集はキャンセルされ、ユーザーにキャンセルの警告が表示されます。

    以下は、上記の検証が IgcGridComponent に適用された結果のデモです。

    スタイル設定

    事前定義されたテーマに加えて、利用可能な CSS プロパティを設定することでグリッドをさらにカスタマイズできます。 一部の色を変更したい場合は、最初にグリッドのクラスを設定する必要があります。

    <igc-grid class="grid"></igc-grid>
    

    次に、そのクラスに関連する CSS プロパティを設定します。

    .grid {
        --ig-grid-edit-mode-color: orange;
        --ig-grid-cell-editing-background: lightblue;
    }
    

    スタイル設定の例

    API リファレンス

    その他のリソース