I have a function which displays an input field only if the select field before has the "Other" selected value:
inputMotor = 'none';
this.f.get('motorType').valueChanges
.subscribe((pVal) => {
pVal === 'Other' ? this.inputMotor = 'flex' : this.inputMotor = 'none';
});
And the template:
<div class="form-group">
<label for="motorType">Motor Type</label>
<select class="form-control" formControlName="motorType" id="motorType" type="text">
<option value="">Choose the Motor Type</option>
<option value="Value 1">Value 1</option>
<option value="Value 2">Value 2</option>
<option value="Other">Other</option>
</select>
</div>
<div class="form-group" [ngStyle]="{'display':inputMotor}">
<input class="form-control" formControlName="otherMotorType" placeholder="Other Motor Type" type="text">
</div>
In the example above, I use the function to recognize the selected value in the "motorType" field. The problem is that this function applies to many selection fields. So, I tried to generate a generic function for this. In my service, I tried:
getField(form, field: string, inputField: string) {
form.get(field).valueChanges
.subscribe((pVal) => {
pVal === 'Other' ? inputField = 'flex' : inputField = 'none';
});
}
And to call the function, I would use:
this.utils.getField(this.f, 'motorType', this.inputMotor);
The call to the component recognizes the first two parameters, but does not update the variable (in the example, inputMotor), always keeping its value as 'none', and not displaying the field for "Other".
I tried as suggested in this post, but it worked fine only for a single variable (it's not reusable).
Also, I'm trying to avoid any code repetition in the component. So, for each form I have, I'm just trying to call the service function and pass the necessary parameters.
How can I achieve this?