IgrGrid では rowSelection プロパティより行選択機能を有効にすることができます。既定の行選択機能を使用しつつ、RowSelectionChanging イベントを使用して特定の行の選択が行われないように制御することが可能です。
ここでは例として、「ID」列の値によって行選択の可否を決定する実装を行います。「ID」列の値が “A” を含む行は選択可、含まない行は不可とするようにします。
RowSelectionChanging イベントを以下のように実装します。
<IgrGrid
ref={gridRef}
id="grid"
primaryKey="ID"
rowSelection="multiple"
onRowSelectionChanging={onRowSelectionChanging}
.....
>
.....
</IgrGrid>
const onRowSelectionChanging = (eventArgs: IgrRowSelectionEventArgs) => {
const event = eventArgs.detail;
if (!event.added.length && event.removed.length) {
// 選択解除の場合は処理を行わない
return;
}
const originalAddedLength = event.added.length;
const newSelectionCloned = Object.assign([], event.newSelection);
const uniqueNewSelection = newSelectionCloned.filter((item : any, index, self) =>
index === self.findIndex((t: any) => (
t.ID === item.ID
))
);
setTimeout(() => {
if (gridRef.current == null) return;
// IDが'A'を含む行のみ選択を許可する
const newSelectionFiltered = uniqueNewSelection.filter(
(x: any) => x.ID.indexOf("A") !== -1
);
const ids: any[] = newSelectionFiltered.map((item: any) => {
return item.ID;
});
gridRef.current.selectRows(ids, true);
// すべての選択可能な行が既に選択済みの場合は選択を全解除する
if (
newSelectionFiltered.length &&
!newSelectionFiltered.filter(
(x: any) => event.oldSelection.indexOf(x) === -1
).length &&
originalAddedLength > 1
) {
gridRef.current.deselectAllRows();
}
}, 0);
}
また、選択不可の行は行セレクターに表示されるチェックボックスを非活性表示とするため、行セレクターのテンプレート( rowSelectorTemplate )を実装します。
<IgrGrid
.....
rowSelectorTemplate={webGridRowSelectorTemplate}>
.....
</IgrGrid>
const webGridRowSelectorTemplate = (ctx: IgrRowSelectorTemplateContext) => {
const contextDetail = ctx.implicit;
const containerStyle = {
justifyContent: "space-evenly",
display: "flex",
width: "64px",
};
// IDが'A'を含む行のみ選択を許可する
const isDisabled = contextDetail.rowID.indexOf("A") === -1;
return (
<div style={containerStyle}>
<IgrCheckbox
checked={contextDetail.selected}
key={contextDetail.key}
disabled={isDisabled}
></IgrCheckbox>
</div>
);
};