我在https://www.ag-grid.com/的示例中构建了自己的cellEditor
,以使Cell仅接受数字输入。这工作正常,但现在键盘导航行为与没有自己cellEditor
的普通文本单元格不同。如果我按左或右键取消EditMode
,则离开单元格并选择另一个,而不是在输入字段中逐步遍历所有字符。我尝试了不同的东西,但我不能让它工作。如何在自己的cellEditor
中实现这种正常行为?
import {Component, ViewContainerRef, ViewChild, AfterViewInit} from '@angular/core';
import {AgEditorComponent} from 'ag-grid-ng2/main';
@Component({
selector: 'numeric-cell',
template: `<input #input (keydown)="onKeyDown($event)" [(ngModel)]="value">`
})
export class NumericEditorComponent implements AgEditorComponent, AfterViewInit {
private params: any;
public value: number;
private cancelBeforeStart: boolean = false;
@ViewChild('input', {read: ViewContainerRef}) public input: any;
agInit(params: any): void {
this.params = params;
this.value = this.params.value;
// only start edit if key pressed is a number, not a letter
this.cancelBeforeStart = params.charPress && ('1234567890'.indexOf(params.charPress) < 0);
}
getValue(): any {
return this.value;
}
isCancelBeforeStart(): boolean {
/*return this.cancelBeforeStart;*/
return false;
}
// will reject the number if it greater than 1,000,000
// not very practical, but demonstrates the method.
isCancelAfterEnd(): boolean {
/*return this.value > 1000000;*/
return false;
};
onKeyDown(event: any): void {
if (!this.isKeyPressedNumeric(event) && !this.isKeyPressedArrow(event)) {
if (event.preventDefault) {
event.preventDefault();
}
}
}
// dont use afterGuiAttached for post gui events - hook into ngAfterViewInit instead for this
ngAfterViewInit() {
this.input.element.nativeElement.focus();
}
private getCharCodeFromEvent(event: any): any {
event = event || window.event;
return (typeof event.which == "undefined") ? event.keyCode : event.which;
}
private isCharNumeric(charStr: any): boolean {
return !!/\d/.test(charStr);
}
private isKeyPressedNumeric(event: any): boolean {
var charCode = this.getCharCodeFromEvent(event);
var charStr = String.fromCharCode(charCode);
return this.isCharNumeric(charStr);
}
private isKeyPressedArrow(event: any): boolean {
console.log("isKeyPressedArrow");
var charCode = this.getCharCodeFromEvent(event);
console.log(charCode);
var bol = this.isKeyArrow(charCode);
console.log(bol);
return this.isKeyArrow(charCode);
}
private isKeyArrow(charStr: any): boolean {
return /^37|38|39|40/.test(charStr);
}
}
答案 0 :(得分:2)
看看ng2-examples repo中提供的MoodEditor:https://github.com/ceolter/ag-grid-ng2-example/blob/master/systemjs_aot/app/mood-editor.component.ts
如果你看一下onKeyDown方法,你会看到它正在寻找左/右击键,如果找到了一些业务逻辑,然后停止编程
onKeyDown(event): void {
let key = event.which || event.keyCode;
if (key == 37 || // left
key == 39) { // right
this.toggleMood();
event.stopPropagation();
}
}
您的主要部分是将event.stopPropagation();
添加到onKeyDown