0
votes

I use a custom cell editor for some columns on my ag-grid for user input validation to prevent non-numeric inputs. My component class:

import { Component, ViewChild } from '@angular/core';


const KEY_TAB = 9;
const ENTER = 13;
const ARROW_RIGHT = 39;
const ARROW_LEFT = 37;

@Component({
  selector: 'app-numeric-editor',
  templateUrl: './numeric-editor.component.html',
  styleUrls: ['./numeric-editor.component.scss']
})
export class NumericEditorComponent {
  @ViewChild('i') textInput;
  params;

  agInit(params: any): void {
    this.params = params;
  }

  getValue() {
    return this.textInput.nativeElement.value;
  }

  onKeyPress(event) {
    if (!isNumeric(event)) {
      event.preventDefault();
    }

    function isNumeric(ev) {
      return /\d/.test(ev.key);
    }
  }

  onKeyDown(event) {
    if (event.keyCode === ARROW_RIGHT ||
        event.keyCode === ARROW_LEFT ||
        event.keyCode === KEY_TAB 
        
      ) {
      event.stopPropagation();
    }
  }

}

The template of the component:

<input
  #i
  [value]="params.value"
  (keypress)="onKeyPress($event)"
  (keydown)="onKeyDown($event)"
  class="ag-theme-alpine-dark"
/>

Now, there are some editing problems with my custom cells. To edit a normal/default cell, I can just (single-)click on it and start writing.

This does not work on my custom cells. On the custom cells, I first have to use double-click to focus the row and then click on the cell for editing. That is kinda inconvenient.

How can I make it work/behave as default?

The same issue is with pressing 'Enter': When clicking on a cell, I just want to press Enter, to focus in and out of the cell for editing. This works fine on default, but not on my custom cells.

Overall, I would like the navigation and editing to behave in the same way as the default cells do.

2

2 Answers

1
votes

You can achieve this by setting the singleClick property on the ag-grid component

<ag-grid-angular
 //...
 [singleClickEdit]="true"
 </ag-grid-angular>

If you are using a custom editor you might need to focus your input after the GUI has been attached to the DOM.

You can define afterGuiAttached callback method in your editor, this will be called by ag-grid.

  afterGuiAttached() {
    this.textInput.nativeElement.focus();
    this.textInput.nativeElement.select();
  }

Here is a working example:

https://plnkr.co/edit/okdFOpuuHJgv9Wtc

numeric-editor.component.ts

0
votes

GridOptions has a property singleClickEdit to allow single-click to start editing instead of double-click https://www.ag-grid.com/javascript-grid-cell-editing/