When using reactive forms with an async validator on the form group, and if changing the values of the form group by using patchValue
in the constructor or in ngOnInit
- even though the async validator observable completes, the form remains in PENDING
state.
I've created a SSCCE in Stackblitz
In the example, you see a simple form with two fields, with an indication of the form status, and the validator state. In the code, in ngOnInit
I call patchValue
on the form, causing the form to go into PENDING
status, and the async validator to be called.
The async validator doesn't do much, it simply waits for 1 second then returns a null
errors object basically saying that the form is valid. You can see in the indications that the validation completed, but the form stays in PENDING
status.
If you trigger a change in field values at any time other than in the constructor or in ngOnInit
(i.e. on object construction) - then the form does go into VALID
status when the validator completes. This also applies if you wrap the value change in setTimeout
.
Am I doing something wrong? Is this normal behavior, or is this a bug in Angular?
patchValue
"too fast" (before the form has been completely built and prev values set), it causes this. So no, not a bug, it is caused by angular forms being asynchronous. There are sometimes other issues caused by forms being asynchrnous, so you sometimes need to wait a tick (using settimeout) before doing something, here's one (unrelated) question https://mcmap.net/q/1916210/-error-alerts-in-angular-reactive-forms-appear-one-step-late – VaricelloidpatchValue
shouldn't be called in the same frame that creates theFormGroup
... – Broadleaved