I have a form with first_name
and last_name
fields.
When both of these fields have a value entered, I wish to enable another formControl in the same form.
I know I can subscribe to the changes like this:
createForm() {
this.myForm = new FormGroup({
first_name: this.first_name,
last_name: this.last_name,
email: this.email,
mobile: this.mobile,
salutation: this.salutation
});
this.myForm.valueChanges.subscribe(data => console.log('form changes', (!data.first_name == !data.last_name)));
}
which logs to the console and shows 'true' when both values are set.
You can see from this thread on angular github that we cannot/should not set that to a property and bind [disabled]=<booleanProperty>
(and the core team seem to still be working on this issue).
So how do I use the result from my valueChanges stream above to actually set the other control to an enabled state?
In the OnInit it is disabled as per the guides:
this.salutation = new FormControl({value:'', disabled: true}, Validators.required);
UPDATE
Sorry I forgot to mention that I already tried this, in the OnInit:
this.myForm.valueChanges.subscribe(data => {
if (!data.first_name == !data.last_name) {
this.salutation.enable();
};
})
That does not work, it throws console error: Maximum call stack size exceeded
Using [disable] Binding We can disable a control using [disabled]="true" binding. We can also disable control using [attr. disabled]="true" . Angular does not suggest to use [disabled]="true" binding to disable a control.
If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors. Example: form = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true}, Validators.
The stack size exceeded was the clue to solving this. Since the stream is 'continuous' my code kept setting the control to enabled - but of course, it only needs to be enabled once.
So adding a check solved the problem, and now it works:
this.myForm.valueChanges.subscribe(data => {
if (!data.first_name == !data.last_name && this.myForm.controls['salutation'].disabled) {
this.myForm.controls['salutation'].enable();
};
})
Further info here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With