#angular #ag-grid
#angular #ag-grid
Вопрос:
Как сделать простой тип ввода =»число» в ячейке ag-grid? что-то вроде этого:
cellRenderer: params => {
if (isNaN(Number(params.value))
{
return params.value.replace(/[^0-9.] /g, '');
} else {
return params.value;
}
}
Ответ №1:
К сожалению, нет ни одного простого способа сделать это. В моем случае я создал отдельный компонент, как на официальной странице ag-grid. Я надеюсь, что в ближайшем будущем они изменят это, потому что сейчас это очень неясно и сложно. Спасибо всем за помощь!
Комментарии:
1. Да, это безумие
Ответ №2:
То, что вы делаете, похоже на «дробовик». Он позаботится о недопустимом вводе не только при редактировании, но даже если при рендеринге (получении данных из источника) будет указано какое-то неправильное значение.
Вы должны определить пользовательский компонент для обработки пользовательского ввода.
var columnDefs = [
{
field: "value",
editable: true,
cellEditorSelector: function (params) {
if (params.data.type === 'age') { // here you can check using your logic if it needs numericCelleditor or not
return {
component: 'numericCellEditor'
};
}
return null;
...
...
Пользовательский компонент редактора Документация по ссылке
// function to act as a class
function NumericCellEditor() {
}
// gets called once before the renderer is used
NumericCellEditor.prototype.init = function (params) {
// create the cell
this.eInput = document.createElement('input');
if (isCharNumeric(params.charPress)) {
this.eInput.value = params.charPress;
} else {
if (params.value !== undefined amp;amp; params.value !== null) {
this.eInput.value = params.value;
}
}
var that = this;
this.eInput.addEventListener('keypress', function (event) {
if (!isKeyPressedNumeric(event)) {
that.eInput.focus();
if (event.preventDefault) event.preventDefault();
} else if (that.isKeyPressedNavigation(event)){
event.stopPropagation();
}
});
// only start edit if key pressed is a number, not a letter
var charPressIsNotANumber = params.charPress amp;amp; ('1234567890'.indexOf(params.charPress) < 0);
this.cancelBeforeStart = charPressIsNotANumber;
};
NumericCellEditor.prototype.isKeyPressedNavigation = function (event){
return event.keyCode===39
|| event.keyCode===37;
};
// gets called once when grid ready to insert the element
NumericCellEditor.prototype.getGui = function () {
return this.eInput;
};
// focus and select can be done after the gui is attached
NumericCellEditor.prototype.afterGuiAttached = function () {
this.eInput.focus();
};
// returns the new value after editing
NumericCellEditor.prototype.isCancelBeforeStart = function () {
return this.cancelBeforeStart;
};
// example - will reject the number if it contains the value 007
// - not very practical, but demonstrates the method.
NumericCellEditor.prototype.isCancelAfterEnd = function () {
var value = this.getValue();
return value.indexOf('007') >= 0;
};
// returns the new value after editing
NumericCellEditor.prototype.getValue = function () {
return this.eInput.value;
};
// any cleanup we need to be done here
NumericCellEditor.prototype.destroy = function () {
// but this example is simple, no cleanup, we could even leave this method out as it's optional
};
// if true, then this editor will appear in a popup
NumericCellEditor.prototype.isPopup = function () {
// and we could leave this method out also, false is the default
return false;
};
Комментарии:
1. Возможно, вы захотите использовать компонент framework , поскольку OP использует angular
Ответ №3:
Самый простой способ до сих пор в ag-grid
// чтобы убедиться, что пользователь ввел только число
valueSetter: (params: ValueSetterParams) => { //to make sure user entered number only
var newValInt = parseInt(params.newValue);
var valueChanged = params.data.age!== newValInt;
if (valueChanged) {
params.data.age= newValInt ? newValInt : params.oldValue;
}
return valueChanged;
},
полный пример кода:
{
headerName: "Age",
field: "age",
width: 100,
editable: true,
sortable: true,
filter: 'agTextColumnFilter',
floatingFilter: true,
floatingFilterComponentParams: { suppressFilterButton: true },
valueSetter: (params: ValueSetterParams) => { //to make sure user entered number only
var newValInt = parseInt(params.newValue);
var valueChanged = params.data.age !== newValInt;
if (valueChanged) {
params.data.age = newValInt ? newValInt : params.oldValue;
}
return valueChanged;
},
},
ВАЖНО
у меня это сработало с angular Typescript.
Ответ №4:
это работает для моего приложения angular: примечание: если пользователь вводит значение «не число» — это значение не будет сохранено (будет сохранено старое значение)
public columnDefs: ColDef[] = [
{ headerName: 'number',
field: 'number',
editable: true,
singleClickEdit: true,
valueParser: this.numberParser
}
]
numberParser(params: ValueParserParams): number | string {
return Number.isNaN(Number(params.newValue)) ? params.oldValue : Number(params.newValue);
}