Ag Grid社区版列值限制失效:可任意输入问题排查
Ag Grid社区版:顶部固定行sport列无法限制输入值的解决办法
我正在使用Ag Grid社区版,想要实现通过顶部固定行添加新行的功能,重点是把sport列的输入值限制为指定列表(无需关注图片)。但目前该列仍可输入任意值,不清楚遗漏了哪些配置?
let rowData = []; let inputRow = {}; function setRowData(newData) { let currData = []; gridOptions.api.forEachNode(node => currData.push(node.data)); currData.push(newData[0]); gridOptions.api.setRowData(currData); } function setInputRow(newData) { inputRow = newData; gridOptions.api.setPinnedTopRowData([inputRow]); } const columnDefs = [ { field: 'athlete' }, { field: 'age' }, { field: 'sport', cellEditorParams: { values: ['Tennis', 'Swimming'], cellEditorPopup: true, }, } ]; const startData = [ {athlete: 'bob', sport: 'Swimming', age: '35'}, {athlete: 'john', sport: 'Tennis', age: '36'}, ] const gridOptions = { rowData: startData, columnDefs: columnDefs, pinnedTopRowData: [inputRow], defaultColDef: { flex: 1, editable: true, valueFormatter: (params) => isEmptyPinnedCell(params) ? createPinnedCellPlaceholder(params) : undefined, }, getRowStyle: ({ node }) => node.rowPinned ? { 'font-weight': 'bold', 'font-style': 'italic' } : 0, onCellEditingStopped: (params) => { if (isPinnedRowDataCompleted(params)) { // save data setRowData([...rowData, inputRow]); //reset pinned row setInputRow({}); } }, }; function isEmptyPinnedCell({ node, value }) { return ( (node.rowPinned === 'top' && value == null) || (node.rowPinned === 'top' && value == '') ); } function createPinnedCellPlaceholder({ colDef }) { return colDef.field[0].toUpperCase() + colDef.field.slice(1) + '...'; } function isPinnedRowDataCompleted(params) { if (params.rowPinned !== 'top') return; return columnDefs.every((def) => inputRow[def.field]); } document.addEventListener('DOMContentLoaded', async () => { const gridDiv = document.querySelector('#mygrid'); new agGrid.Grid(gridDiv, gridOptions); })
问题原因与解决办法
问题出在你没有指定sport列的单元格编辑器类型。Ag Grid默认使用文本编辑器,所以即使配置了cellEditorParams.values也不会生效——只有选择器类的编辑器才会读取这个参数。
在Ag Grid社区版中,你需要为sport列添加cellEditor: 'agSelectCellEditor'配置,这是官方提供的下拉选择编辑器,会严格使用你定义的values列表作为可选值,无法输入自定义内容。
修改后的sport列定义如下:
{ field: 'sport', cellEditor: 'agSelectCellEditor', // 新增该行指定编辑器类型 cellEditorParams: { values: ['Tennis', 'Swimming'], cellEditorPopup: true, }, }
补充注意事项
- 确保
inputRow初始状态下,sport字段为空或者是列表中的有效值,避免编辑器初始化时出现异常 - 如果需要支持搜索等更复杂的选择功能,社区版可以自定义单元格编辑器,但基础场景使用
agSelectCellEditor完全满足需求
内容的提问来源于stack exchange,提问作者mHelpMe
相关产品推荐
相关产品推荐

