I'm using Angular 11.0.2. I have a form group with 20 fields that are displayed in two tables. Some of this formControls are shared between two forms.
~9 of those formControls are text input fields that I would like to observe. When a value changes, I would like to fire an event. However, the tricky part is that there are 3 fields I would like to process individually (each in a different way). Therefore subscribing to the whole form group doesn't cut it. For the remaining 6 fields, I also need to know their field name, to process it further.
My ideas are:
- Subscribe to each formControl individually and create an update method for each of them. However, this will result in an abundance of fields and methods. Example in my TS class:
ngOnInit(): void {
this.direction$ = this.weatherForm.get('direction').valueChanges.subscribe(() => this.updateDirectionChange());
this.speed$ = this.weatherForm.get('speed').valueChanges.subscribe(() => this.updateSpeedChange());
}
- Use
(change)event on each form control input field, passing the field name, and dealing with it within the TS calls with control flow. This one seems to make the template unnecessarily complex with logic. Example in my template:
<tr class='table-row'>
<td
class='table-cell caption grayscale secondary-text'>Direction</td>
<td class='table-cell'>
<input-field>
<input input class='weather-input-field' formControlName='direction' (change)='handleFieldChange("direction")'/>
</input-field>
</td>
</tr>
<tr class='table-row'>
<td
class='table-cell caption grayscale secondary-text'>Speed</td>
<td class='table-cell'>
<input input class='weather-input-field' formControlName='speed' (change)='handleFieldChange("speed")'/>
</td>
</tr>
However, none of those ways seems to be efficient or be "clean code" from my perspective. Are there any better ways to handle it? If not, what would be your preferred solution?
Thank you in advance.
I like use some like
$obs return an object in the way,e.g.
{id:"one":value:"what-ever"}But I feel that there're a better approach that is use ngModel in your form to change the value of the two formControls. So you can
See how the input get the value of the formControl "one" and, when change, change the value of the formControl "one" of the form1, and the formControl "one" of the form2