I have a FormGroup with multiple nested groups and controls. Most of these contain validators such as Validators.required. Whenever the user clicks the submit button, I recursively loop through the form to make sure each validator is triggered and each control is valid. This is done by marking each control as touched and calling control.updateValueAndValidity().
However, this triggers both the valueChanged and statusChanged event. I have added subscribers to the statusChanged event which should handle any errors but I do not wish to trigger valueChanged since the value did not change.
Would it be possible to manually fire statusChanged without firing valueChanged? Passing { emitEvent: false } to updateValueAndValidity would prevent both events from being fired.
public ngOnInit(): void {
const form = this.formBuilder.group({
'name': ['', Validators.required],
'address': this.formBuilder.group({
'street': ['', Validators.required],
'number': ['', Validators.required]
})
});
form.valueChanges.subscribe(() => console.log('Should not fire'));
form.statusChanges.subscribe(() => console.log('Should fire'));
this.validateForm(form);
console.log(form.valid);
}
private validateForm(control: AbstractControl): void {
if (control instanceof FormControl) {
control.markAsTouched();
control.markAsDirty();
control.updateValueAndValidity();
} else if (control instanceof FormGroup) {
Object.keys(control.controls).forEach(field => {
this.validateForm(control.get(field));
});
}
}
// should print 'Should fire' and 'false' but not 'Should not fire'