Reputation: 305
When dynamically adding a new FormControl with asyncValidation to a reactive form the form goes from PENDING to VALID/INVALID but statusChanges is not trigger.
I have a form that is dynamically modified and, after that happen, I subscribe to statusChanges. I'm printing the form's status and I can check that the status changes but stausChanges is not trigger.
Here is an example https://stackblitz.com/edit/angular-pvebmb?file=src%2Fapp%2Fapp.component.ts .
In this example you can check that there is a subscription to console.log for statusChanges. There is a button that, when clicked, adds a new FormControl with a async validation that takes 1 second to complete. You can check that, when you click in the button the form's status (that is printed in the html) goes from PENDING to INVALID but no console.log related to the statusChanges is printed.
I expected to get statusChanges triggered every time the form's status value changes.
Upvotes: 7
Views: 10641
Reputation: 675
I have similar issue when user does not input anything and click submit button, my validators do not fire error messages when the message component is relying on listening the input's statusChanges. (Note: maybe my validation is not async validation)
My solution is calling the following function when the submit button is clicked, and it works:
validateAllFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
control.updateValueAndValidity();
}
});
}
Upvotes: 1
Reputation: 1485
It looks like it is done by design. It is not firing the status change because it is invalid on initialization (or on the first run of updateValueAndValidity
), and if you check the code of FormControl, that event is going to be prevented to be emitted. You can check it here:
https://github.com/angular/angular/blob/8.2.13/packages/forms/src/model.ts#L1275
As you can see, emitEvent
is false.
This doesn't really solve your problem, but at least explains why is it happening. In your example, if you set the value to an empty value right after pushing the control, you will get that statusChange, because that time updateValueAndValidity
will have emitEvent
set to true. So a workAround would be setValue of the formControl to empty if you really want that statusChanges to fire on initialization.
Upvotes: 8