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'
statusChanges
to listen for validation changes. Whenever it's triggered, I check for any validation errors and show them to the user. According to the angular docs this is "a multicasting observable that emits an event every time the validation status of the control recalculates", which seems perfect for what I used it for. If I didn't call validateForm, valueChanges would never be triggered and no validation messages would be shown. – Pathogenic<div *ngIf="name.errors.forbiddenName">Name cannot be Bob.</div>
. You just have to prevent submitting the form if invalid. – KenethstatusChanges
and handles showing messages. – Pathogenic