[Fixed] How to detect changes in the bound form variable value in a custom form control (Angular 10)

Issue

I’ve created an Angular custom form component that implements the ControlValueAccessor interface so it can be used like this:

<form [formGroup]="formModel">
  <my-custom-control formControlName="config_name"
    label="{{ 'INPUT_CONFIG.LABEL' | translate }}"></my-custom-control>

</form>

The component needs to do some logic whenever the config_name form variable changes. How could I detect this change inside the custom component (not the parent)?

I’ve tried implementing the OnChanges interface, but the SimpleChanges object received doesn’t have any reference to the bound form variable.

Thanks in advance,

Solution

I had the solution just before my eyes: the writeValue method implemented from the ControlValueAccessor does exactly what I need but I misunderstood the documentation. Now I can parse whatever value the custom form control gets:

writeValue(newValue: string) {
  if(newValue) {
    this.parseNameValue(newValue); // Do the needed logic to parse the value
  } else {
    this.value = '';
  }
}

Cheers,

Leave a Reply

(*) Required, Your email will not be published