0

I have an Angular 14 web application that is using reactive forms and I am in a situation where the component that I use to edit a certain field expects the data in a different format than the one in the form.

Let me make a very simple example to explain the this better. Let's assume I have a form where there is a field that is an array of strings, like this:

this.myForm = this.formBuilder.group({
  myField: [['foo', 'bar', 'asd']],
  ...
});

However, let's say (again: simple example) I would like to edit this with a text input in comma-separated form, so it would look something like this:

enter image description here

Now, I know this can be achieved by creating a dedicated editing component that implements ControlValueAccessor and the various associated methods.

However, I'm wondering if there is a simpler way with less overhead, since for something like this I would not need custom UI, I would just need a "bridge" that converts the form value to a comma-separated string when the input is populated and, vice-versa, converts back the comma-separated string to an array when the input changes and the value is written back to the form control.

For example, when I work with WPF (Windows Presentation Foundation) I can achieve stuff like this very easily by implementing the IConverter interface that exposes the Convert and ConvertBack methods and set an instance of it in any data-binding expression.

Is anything similar achievable in Angular Forms?

Master_T
  • 7,232
  • 11
  • 72
  • 144
  • 1
    AngularJS used to have formatters and parsers for exactly this purpose. In Angular, you have to go with ControlValueAccessor (it doesn't need to be a component, it can be a template directive). – mbojko Jul 20 '23 at 13:51
  • Thanks for the info, any guide/documentation on how to implement ControlValueAccessor without a component? All the guides I find online tend to create a dedicated component. – Master_T Jul 21 '23 at 08:47
  • 1
    Here's one example (quite ancient, but still): https://stackoverflow.com/questions/40694521/angular-2-directive-implementing-controlvalueaccessor-doesnt-update-touched-p – mbojko Jul 21 '23 at 12:19

0 Answers0