I want to uncheck a checkbox any time there is a change in the form. The checkbox is part of that form so I want to only uncheck it when value change comes from any other control aside from that checkbox.
I am subscribing to a FormGroup's value changes like so
import { FormBuilder, FormGroup } from '@angular/forms';
export class App {
form : FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = formBuilder.group({
firstName: 'Thomas',
lastName: 'Mann',
... many more fields ...
checkbox: true
})
this.form.valueChanges.subscribe(data => {
//if valueChange was not triggered by change in the checkbox
this.form.get('checkbox').setValue(false);
})
}
}
I could subscribe to valueChanges in every other control individually, but would like to avoid doing so
Use nested form group... Group all other formControl in single formGroup on which you want to update your checkbox value...
For example :
import { FormBuilder, FormGroup } from '@angular/forms';
export class App {
form : FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = formBuilder.group({
'otherFormField': this.fb.group({
firstName: 'Thomas',
lastName: 'Mann',
... many more fields ...
}),
checkbox: true
})
this.form.otherFormField.valueChanges.subscribe(data => {
//if valueChange was not triggered by change in the checkbox
this.form.get('checkbox').setValue(false);
})
}
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