我有这个网格选项:
gridOptions: GridOptions = {
suppressFieldDotNotation: true,
paginationAutoPageSize: false,
paginationPageSize: 10,
domLayout: 'autoHeight',
rowMultiSelectWithClick: false,
rowSelection: 'multiple',
onFilterChanged: (event) => this.onFilterChanged(event),
onCellValueChanged: (event) => this.onCellValueChanged(event)
} as GridOptions;
关于单元格值,我有这个:
onCellValueChanged(event) {
if (typeof event.newValue === 'string') {
this.toastrService.error(event.newValue + ' is not a number!');
return;
}
}
只有一列是可编辑的,我想要的是用户输入一些不是数字或小数的值,例如 (1, 1.1, 1,1),我将该列设置为零,并显示消息。< /p>
我试过这样,但它显示十进制值 1.1 和 1,2(带点和逗号)的验证消息,另一个问题是,如果验证为假,我不知道如何将该行上的该列设置为零。
有什么建议吗?
答案 0 :(得分:1)
不幸的是,没有直接的配置属性可以做到这一点。
我们必须创建一个新的单元格编辑器组件并将其注册到 columnDefs 中的列。
是这样的: 在这个例子中,我们可以通过三种方式来操作数据。
这里,首先,由于输入类型是数字,所以只有数字条目 将被允许。
如果您不想这样做,请检查输入值是否为 数与否。如果不是,则赋值为零。
第三,如果值不正确,请勿编辑。
import {
AfterViewInit,
Component,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import { AgEditorComponent } from 'ag-grid-angular';
@Component({
selector: 'editor-cell',
template: `<input
type="number" #########check1
[(ngModel)]="value"
#input
style="width: 100%"
/>`,
})
export class PercentageCellEditor implements AgEditorComponent, AfterViewInit {
private params: any;
public value: number;
@ViewChild('input', { read: ViewContainerRef })
public input: ViewContainerRef;
ngAfterViewInit() {
// focus on the input
setTimeout(() => this.input.element.nativeElement.focus());
}
agInit(params: any): void {
this.params = params;
}
/* Component Editor Lifecycle methods */
// the final value to send to the grid, on completion of editing
getValue() {
// check2
this.value = !Number.isNaN(parseFloat(this.params.value)) ? parseFloat(this.params.value) : 0;
return this.value;
}
// Gets called once before editing starts, to give editor a chance to
// cancel the editing before it even starts.
isCancelBeforeStart() {
return false;
}
// Gets called once when editing is finished (eg if enter is pressed).
// If you return true, then the result of the edit will be ignored.
isCancelAfterEnd() {
// check3
return (this.value < 0 || this.value >= 100);
}
}
组件:
在grid的frameworkComponents中注册。
this.frameworkComponents = {
percentageEditor: PercentageCellEditor
}
将其添加到 columnDefs:
{
headerName: "Column Name",
field: "columnFieldName",
editable: true,
cellEditor: "percentageEditor",
}
答案 1 :(得分:0)
使用 Value Setters 进行基本验证,如下例所示:https://plnkr.co/edit/lRxzoiYSAjtsOAKX
如果输入的值不是数字或大于 100,则不会保存到网格并显示警告:
valueSetter: (params) => {
if (isNaN(params.newValue)) {
alert('not valid number');
return false;
}
if (params.newValue > 100) {
alert('input is larger than 100');
return false;
} else {
params.data.numberGood = params.newValue;
return true;
}
},