Search code examples
ag-gridangular-directivecontrolvalueaccessor

focus event is getting called before writeValue() when using custom directive inside ag-Grid cell Editor


Goal: Make ag-Grid cell editable as a currency control.

Approach:

  1. Created a custom directive for currency.
  2. Created a custom cell editor, which uses that currency directive.

Issue:

In a normal scenario, on page load, control with directive (implements ControlValueAccesor) loads and writeValue() is called to initialize the value in the control. So, I'm displaying the value with the currency($) symbol using writeValue(). And when, user clicks on the control, I'm displaying the value without currency symbol by writing the logic in focus event.

Now, with ag-Grid, directive would not load on page load. It would load when control is clicked, since it is enclosed within a cell editor. So, on click/focus, the following gets called in the following order -

  1. focus event - It would set the control value to null, since no value has been set yet using writeValue. But soon after that, writeValue() is called.
  2. writeValue() - It would set the control value to the value with $ symbol, which I don't want. I want value without the $ symbol, on focus.

So, how can I call writeValue() before the focus event of the directive?

Note: Btw, 2-click functionality of cell-editor is working fine but I want 1-click solution, as I have set the focus on the control in afterGuiAttached().


Solution

  • I was able to figure out the solution by using setTimeout:

     public afterGuiAttached(): void {
        // Set focus after the value has been written into the control
        setTimeout(() => {
          this.input.nativeElement.focus();
        });
     }

    Couldn't find any better solution. Let me know if you guys know or find any better solution. Thanks.