How do I intercept the value of the FormControl before setting or getting it?

The question is pretty clear. I would like to intercept the incoming value for the value property of the FormControl and be able to intercept the outgoing value into the HTML control it connected to.

Let's say I have a FormControl named "firstName" and I connect it to a textbox as such:

<input type="text" formControlName="firstName" />

      

By default, when the user enters a value in the text box and submits, the FormControl value gets the value in the text box. Is there a way to intercept the value to be set and change it before setting it?

Likewise, is there a way to intercept the value that the FormControl is sending to the HTML control? For example, if I have a FormControl value set to something, but I want to change the value that appears in the textbox.

I know that I can use ngModel to work as an intermediary between the form and the control, but this becomes cumbersome when using multiple controls. I also know that you can create your own control and implement ControlValueAccessor, but this is also cumbersome as I would have to create an appropriate control for every control I want to use.

For more details on why I am asking this question see https://github.com/ionic-team/ionic/issues/7121

+3


source to share


1 answer


You can use onBlur to call the function (i.e. modifyValue()

) and then use patchValue to change the value:

<input type="text" onblur="modifyValue()" formControlName="firstName" />

modifyValue() {
    this.form.patchValue({
      firstName: this.form.firstName //modify firstName here
    })
}

      



If that works, you can create a generic function and pass the key / value to fix without creating a bunch of specific functions.

<input type="text" onblur="modifyValue('firstName')" formControlName="firstName" />

  modifyValue(key) {
      this.form.controls[key].patchValue(this.form.controls[key] // modify value here)
  }

      

0


source







All Articles