如何在ag-grid中的数字(仅数字)单元格上退格?

时间:2019-06-25 18:37:39

标签: angular typescript input ag-grid

以AG-Grid慷慨提供的示例为例[https://next.plnkr.co/edit/Gbwc2rBQKJRFbLxS?preview],我目前正在尝试使用数字编辑器。

此示例来自ag-grid官方网站[https://www.ag-grid.com/javascript-grid-cell-editor/#example-cell-editing-using-angular-components]

我注意到的一件事甚至是在AG-Grid提供的示例中,退格键也不起作用。

我刚接触AG-Grid,将不胜感激!

这是我正在使用的numeric-editor.ts:

import {AfterViewInit, Component, ViewChild, ViewContainerRef} from 
"@angular/core";

import {ICellEditorAngularComp} from "ag-grid-angular";

@Component({
    selector: 'numeric-cell',
    template: `<input #input (keydown)="onKeyDown($event)" 
[(ngModel)]="value" style="width: 100%">`
})
export class NumericEditor implements ICellEditorAngularComp, 
AfterViewInit {
    private params: any;
    public value: number;
    private cancelBeforeStart: boolean = false;

    @ViewChild('input', {read: ViewContainerRef}) public input;


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;
}

// will reject the number if it greater than 1,000,000
// not very practical, but demonstrates the method.
isCancelAfterEnd(): boolean {
    return this.value > 1000000;
};

onKeyDown(event): void {
    if (!this.isKeyPressedNumeric(event)) {
        if (event.preventDefault) event.preventDefault();
    }
}

// dont use afterGuiAttached for post gui events - hook into 
ngAfterViewInit instead for this
ngAfterViewInit() {
    window.setTimeout(() => {
        this.input.element.nativeElement.focus();
    })
}

private getCharCodeFromEvent(event): any {
    event = event || window.event;
    return (typeof event.which == "undefined") ? event.keyCode : 
event.which;
}

private isCharNumeric(charStr): boolean {
    return !!/\d/.test(charStr);
}

private isKeyPressedNumeric(event): boolean {
    const charCode = this.getCharCodeFromEvent(event);
    const charStr = event.key ? event.key : 
String.fromCharCode(charCode);
    return this.isCharNumeric(charStr);
}
}

1 个答案:

答案 0 :(得分:0)

private isCharNumeric(charStr): boolean {
    return !!/\d/.test(charStr) || charStr === 'Backspace';
}

在ischarnumeric函数上添加退格键就可以了!