Angular TS中dx-data-grid新增/编辑行错误数据的背景色设置与编辑拦截
Angular dx-data-grid 行校验与编辑拦截实现
核心实现思路
- 通过
onRowPrepared事件动态标记错误行背景色 - 在
onRowUpdating/onRowInserting事件中校验数据,阻止错误行退出编辑状态
步骤1:更新组件模板
添加onRowPrepared事件绑定,同时完善列配置示例:
<dx-data-grid [dataSource]="dataSource" keyExpr="id" (onRowInserted)="onRowInserted($event)" (onRowUpdating)="onRowUpdating($event)" (onRowInserting)="onRowInserting($event)" (onRowUpdated)="onRowUpdated($event)" (onRowPrepared)="onRowPrepared($event)"> <!-- 业务列配置,根据实际需求调整 --> <dxi-column dataField="name" caption="名称"></dxi-column> <dxi-column dataField="value" caption="数值"></dxi-column> <!-- 编辑操作列 --> <dxi-column type="buttons"> <dxi-button name="edit"></dxi-button> <dxi-button name="delete"></dxi-button> </dxi-column> </dx-data-grid>
步骤2:添加CSS样式(推荐用类代替内联样式)
在组件样式文件中定义错误行样式:
.error-row { background-color: rgba(255, 0, 0, 0.1) !important; }
步骤3:TypeScript逻辑实现
3.1 自定义行数据校验函数
根据业务规则实现校验逻辑,示例中检查必填字段和数据格式:
private validateRowData(rowData: any): boolean { // 示例规则:名称不能为空,数值必须为有效数字 if (!rowData.name || rowData.name.trim() === '') { return false; } if (rowData.value == null || isNaN(Number(rowData.value))) { return false; } // 可添加更多业务校验规则 return true; }
3.2 错误行背景色标记
通过onRowPrepared事件判断行状态并应用样式:
onRowPrepared(e: any): void { // 仅针对编辑中或新增的行进行校验 if ((e.rowType === 'data' && e.isEditing) || e.isNewRow) { const isValid = this.validateRowData(e.data); // 添加/移除错误样式类 if (isValid) { e.rowElement.classList.remove('error-row'); } else { e.rowElement.classList.add('error-row'); } } }
3.3 阻止错误行退出编辑状态
在更新和插入事件中校验数据,不通过则取消操作:
onRowUpdating(e: any): void { // 合并原始数据与修改后的数据,确保校验完整 const updatedRow = { ...e.oldData, ...e.newData }; const isValid = this.validateRowData(updatedRow); if (!isValid) { // 取消更新操作,保持编辑状态 e.cancel = true; // 可选:提示用户错误信息 alert('行数据存在空值或格式错误,请修正后再保存'); } } onRowInserting(e: any): void { const isValid = this.validateRowData(e.data); if (!isValid) { // 取消插入操作,保持新增行编辑状态 e.cancel = true; alert('新增行数据存在空值或格式错误,请修正后再保存'); } }
注意事项
- 校验函数
validateRowData需根据实际业务需求调整规则 - 若使用DevExtreme内置校验规则,可结合列的
validationRules配置,但自定义函数更灵活 - 提示信息可替换为项目中统一的弹出组件(如Toast),提升用户体验
内容的提问来源于stack exchange,提问作者ODTÜ Computer Eng. Student
相关产品推荐
相关产品推荐

