I have a reactive form of some inputs and select element , the role is to disable or enable so input base on the value of select.
this.form.get('option').valueChanges.subscribe((value: string) => {
if (value === 'value1') {
this.form.get('input01').disable();
this.form.get('input02').disable();
this.form.get('input03').disable();
} else {
this.form.get('input01').enable();
this.form.get('input02').enable();
this.form.get('input03').enable();
}
});
My form have 10 inputs like that. so I have 10 lines of code for enable and 10 lines of code for disable. I was looking for a way to refactor this code to something like setValue
method like set all the elements of the form to disable or enable, based on the value given in if condition, or suggest me if there is any other better way.
Thanks;
You can add all the associated controls under a FormGroup, and then you can just disable and enable them.
Let say we have this HTML:
So we have one form which contains input and another group of two inputs, so you want to disable only the two inputs.
Code:
So when we press on the top button, it is call the toggle function and its check if the group already disabled, then it enable it, and the same for the opposite direction.
I assumed that you dont want to disable all the form controls, just a portion of inputs. But if you do like to disable and enable the whole form, you can just get rid of the other nested group and do the same for the group.
In your case, you do the same, instead of the button toggle, your have to do it inside the subscription.
Good luck !
In my case I have to disable some form controls based on the selected value of dropdown list, my solution is to call disable / enable method base on the value like this
and we can short this
value === 'testValue' ? 'enable' : 'disable'
be create a cutome functionfinal solution